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)
问题:
你正在寻找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)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |