我有一个数据框,其中一列包含 'weak=30'
类型字符串,我想提取 =
字符串后面的数字并创建名为 数字
。
我使用re.search
来查找数字,但到目前为止它给出了错误。
示例数据
import pandas as pd
import re
raw_data = {'patient': [1, 2, 3,4, 6],
'treatment': [0, 1, 0, 1, 0],
'score': ['strong=42', 'weak=30', 'weak=12', 'pitt=12', 'strong=42']}
df = pd.DataFrame(raw_data, columns = ['patient', 'treatment', 'score'])
df
patient treatment score
0 1 0 strong=42
1 2 1 weak=30
2 3 0 weak=12
3 4 1 pitt=12
4 6 0 strong=42
所以我尝试了
df=df.assign(digits=[int(re.search(r'\d+', x)) for x in df.score])
TypeError: int() argument must be a string, a bytes-like object or a number, not 're.Match'
在 R 中你可以做到
mutate(digits=as.numeric(gsub(".*=","",score))
python pandas
中的等效函数是什么?
预期输出
patient treatment score digits
0 1 0 strong=42 42
1 2 1 weak=30 30
2 3 0 weak=12 12
3 4 1 pitt=12 12
4 6 0 strong=42 42
最佳答案
您可以只使用 str.replace
使用您的 R 正则表达式:
df['digits'] = df['score'].str.replace(r'.*=', '').astype(int)
.*=
模式匹配除换行符之外的所有 0+ 字符,尽可能多地匹配到最后一个 =
和 replace
使用 ''
删除此文本。
或者,您可以使用提取字符串末尾 =
后面的数字的方法:
df['digits'] = df['score'].str.extract(r'=(\d+)$', expand=False).astype(int)
此处,=(\d+)$
匹配 =
,然后将任何一个或多个数字捕获到第 1 组中,然后断言字符串末尾的位置。
这两种情况的输出是:
>>> df
patient treatment score digits
0 1 0 strong=42 42
1 2 1 weak=30 30
2 3 0 weak=12 12
3 4 1 pitt=12 12
4 6 0 strong=42 42
关于python - 提取pandas数据框中某些字符后的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330993/