python - 将 pandas 中的正则表达式值转换为 0 或 1

标签 python regex pandas series

我有下面的 pandas 专栏。我需要将包含单词“anaphylaxis”的单元格转换为 1,将不包含单词的单元格转换为 0。

到现在为止我已经尝试过了,但是还缺少一些东西

df['Name']= df['Name'].replace(r"^(.(?=anaphylaxis))*?$", 1,regex=True)
df['Name']= df['Name'].replace(r"^(.(?<!anaphylaxis))*?$", 0, regex=True)


ID             Name
84      Drug-induced anaphylaxis
1041    Acute anaphylaxis
1194    Anaphylactic reaction
1483    Anaphylactic reaction, due to adverse effect o...
2226    Anaphylaxis, initial encounter
2428    Anaphylaxis
2831    Anaphylactic shock
4900    Other anaphylactic reaction

最佳答案

使用str.contains 进行不区分大小写的匹配。

import re
df['Name'] = df['Name'].str.contains(r'anaphylaxis', flags=re.IGNORECASE).astype(int)

或者,更简洁地说,

df['Name'] = df['Name'].str.contains(r'(?i)anaphylaxis').astype(int)

df
     ID  Name
0    84     1
1  1041     1
2  1194     0
3  1483     0
4  2226     1
5  2428     1
6  2831     0
7  4900     0
当您还想执行基于正则表达式的匹配时,

contains 很有用。虽然在这种情况下,您可以通过添加 regex=False 来完全摆脱正则表达式以获得更高的性能。


但是,要获得更多 性能,请使用列表理解。

df['Name'] = np.array(['anaphylaxis' in x.lower() for x in df['Name']], dtype=int)

甚至更好,

df['Name'] = [1 if 'anaphylaxis' in x.lower() else 0 for x in df['Name'].tolist()]

df

     ID  Name
0    84     1
1  1041     1
2  1194     0
3  1483     0
4  2226     1
5  2428     1
6  2831     0
7  4900     0

关于python - 将 pandas 中的正则表达式值转换为 0 或 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005760/

相关文章:

javascript - 英国电话号码的正则表达式 - 所有可能选项的变体

javascript - 如何在数字正则表达式中允许空格?

python - 在python中根据终端宽度制表?

python - 这是什么意思? xarray 错误 : cannot handle a non-unique multi-index

python - 在 Flask 中生成动态 Pygal 图表

python - 新的 Dataframe 列作为其他行的通用函数 (pandas)

python - 如何使用 matplotlib 绘制与比例无关的箭头

PHP preg_match 只允许数字、空格 '+' 和 '-'

python - 如何按多个级别的列过滤多索引数据框?

python - mkdocs:如何附加可下载文件