Python-检查列是否包含列表中的值,返回值

标签 python pandas

我有一个 df:

d = {'id': [1,2,3,4,5,6,7,8,9,10],
      'text': ['bill did this', 'jim did something', 'phil', 'bill did nothing',
               'carl was here', 'this is random', 'other name',
               'other bill', 'bill and carl', 'last one']}
df = pd.DataFrame(data=d)

我想检查列是否包含列表中的值,其中列表是:

list = ['bill','carl']

我想返回这样的东西

id  text                    contains
1   bill did this           bill
2   jim did something       
3   phil                
4   bill did nothing        bill
5   carl was here           carl
6   this is random
7   other name
8   other bill              bill
9   bill and carl           bill
9   bill and carl           carl
10  last one

尽管处理同一行中的 2 个或更多名称的方式可能会发生变化。 有什么建议吗?

最佳答案

您可以创建一个 lambda 函数来检查列表中的每个项目:

d = {'id': [1,2,3,4,5,6,7,8,9,10],
      'text': ['bill did this', 'jim did something', 'phil', 'bill did nothing',
               'carl was here', 'this is random', 'other name',
               'other bill', 'bill and carl', 'last one']}
df = pd.DataFrame(data=d)

l = ['bill','carl']

df['contains'] = df['text'].apply(lambda x: ','.join([i for i in l if i in x]))

如果您需要列表,可以删除连接,否则它只会连接以逗号分隔的值。

输出

>>df['contains']

0         bill
1             
2             
3         bill
4         carl
5             
6             
7         bill
8    bill,carl
9             
Name: contains, dtype: object

关于Python-检查列是否包含列表中的值,返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938873/

相关文章:

python - 如何将填充应用于1?

python setup.py 卸载

python - 如何跨模块存储应用程序设置

python - 以编程方式测试来自 python 安装脚本的 openmp 支持

python - 执行合并,同时存储所有其他数据并保留原始数据的顺序

python - 带混合小数的列

python - 获取每组行的权重

python - Python 中 geoalchemy2 的 Spatialite 后端

python - 随机森林模型拟合

python - Pandas 数据框根据键减少/添加行