在特定字符后从字符串中提取数字

ali*_*aca 4 python regex string pandas

我有一个数据帧(约100万行),其中包含一个列('Product'),其中包含'none','q1','q123'或'q12_a123'等字符串.

我想提取字母'q'后面的数字并将其输入另一列('AmountPaid'),以便它看起来如下所示:

'Product'    'AmountPaid'
 none            0
 q1              1
 q123            123
 q12_a123        12
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有:

for i in range(0,1000000):
   if 'q' not in df.loc[i,'Product']:
      df.loc[i,'AmountPaid']=0
   else:
      # set 'AmountPaid' to the number following 'q'
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 如何在字母"q"之后立即提取数字,但不一定是之后的所有内容?例如,从'q12_a123'中提取12.
  2. 大多数'AmountPaid'条目将被设置为0.是否有比for循环和if/else语句更有效的方法?

cs9*_*s95 5

你正在寻找str.extract角色的后视'q'.

df['AmountPaid'] = df.Product.str.extract(
      r'(?<=q)(\d+)', expand=False
).fillna(0).astype(int)
Run Code Online (Sandbox Code Playgroud)

df

    Product  AmountPaid
0      none           0
1        q1           1
2      q123         123
3  q12_a123          12
Run Code Online (Sandbox Code Playgroud)