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

时间:2018-03-23 22:11:53

标签: python regex string pandas

我有一个数据框(约100万行),其中包含一列('产品'),其中包含' none'' q1',& #39; q123',或' q12_a123'。

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

'Product'    'AmountPaid'
 none            0
 q1              1
 q123            123
 q12_a123        12

到目前为止,我有:

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'

问题:

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

1 个答案:

答案 0 :(得分:5)

您正在寻找str.extract,并在角色'q'上留意。

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

df

    Product  AmountPaid
0      none           0
1        q1           1
2      q123         123
3  q12_a123          12