在 Pandas 数据框中,我想逐行搜索多个字符串值。如果该行包含一个字符串值,则该函数将为该行添加/打印到 df 1 或 0 末尾的空列中
有多个教程介绍如何选择与(部分)字符串匹配的 Pandas DataFrame 行。
例如:
import pandas as pd
#create sample data
data = {'model': ['Lisa', 'Lisa 2', 'Macintosh 128K', 'Macintosh 512K'],
'launched': [1983,1984,1984,1984],
'discontinued': [1986, 1985, 1984, 1986]}
df = pd.DataFrame(data, columns = ['model', 'launched', 'discontinued'])
df
我从这个网站上提取上面的例子: https://davidhamann.de/2017/06/26/pandas-select-elements-by-string/
我如何对整行进行多值搜索:“int”、“tos”、“198”?
然后打印到 next discontinued 列中,根据行是否包含该关键字,列 int 将具有 1 或 0。
最佳答案
如果你有
l=['int', 'tos', '198']
然后您使用 str.contains
通过加入 '|'
来获取包含任何这些词的每个模型
df.model.str.contains('|'.join(l))
0 False
1 False
2 True
3 True
编辑
如果打算按照@jpp 的解释检查所有列,我建议:
from functools import reduce
res = reduce(lambda a,b: a | b, [df[col].astype(str).str.contains(m) for col in df.columns])
0 False
1 True
2 True
3 True
如果你想把它作为一个具有整数值的列,就这样做
df['new_col'] = res.astype(int)
new_col
0 0
1 1
2 1
3 1
关于python - 在 python pandas 中搜索整行 Dataframe 的多个字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50845987/