python - 提取pandas数据框中某些字符后的数字

标签 python regex pandas search extract

我有一个数据框,其中一列包含 '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/

相关文章:

python - SocketServer.TCPSocket 适用于 stock python,但不适用于使用更新的 OpenSSL 针对 MSVCRT100 编译的 python

python - wget 给出响应 ERROR : 418 unused

java - 为什么我的正则表达式匹配但不捕获组?

php - 在 PHP 中创建脚本解析器

python - pandas 数据框中的条件

python - django 在 syncdb 时不加载初始固定装置

python - 即使整个管道都安装了,管道中的 Sklearn 组件也没有安装?

javascript - 解析 AT 命令的正则表达式

python - 数据框分层索引加速

python - Pandas 数据框中列表中的元素计数