【发布时间】:2020-02-08 09:01:12
【问题描述】:
我有一个数据框,其中一列包含'weak=30' 类型的字符串,我想提取= 字符串之后的数字并创建名为digits 的新列。
我使用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() 参数必须是字符串、类似字节的对象或数字,而不是 '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
【问题讨论】:
-
df.join(df['score'].str.extract(r'=(?P<digits>\d+)$')) -
@user3483203 感谢您的解决方案。您能否详细说明
?P代表什么? -
这是你如何设置捕获组返回的系列的名称。查找命名的正则表达式捕获组,
pandas只是使用该语法
标签: python regex pandas search extract