我有下面的 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/