小编ali*_*aca的帖子

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

我有一个数据帧(约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语句更有效的方法?

python regex string pandas

4
推荐指数
1
解决办法
118
查看次数

标签 统计

pandas ×1

python ×1

regex ×1

string ×1