如何筛选包含特定项目的列表的DataFrame列 [英] How to filter a DataFrame column of lists for those that contain a certain item

查看:2454
本文介绍了如何筛选包含特定项目的列表的DataFrame列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想为包含某个特定术语的字符串过滤一列字符串,我可以这样做:

If I want to filter a column of strings for those that contain a certain term I can do so like this:

df = pd.DataFrame({'col':['ab','ac','abc']})
df[df['col'].str.contains('b')]

返回:

   col
0   ab
2  abc

如何为包含特定项目的列表过滤列表列?例如,来自

How can I filter a column of lists for those that contain a certain item? For example, from

df = pd.DataFrame({'col':[['a','b'],['a','c'],['a','b','c']]})

如何获取所有包含"b"的列表?

how can I get all lists containing 'b'?

         col
0     [a, b]
2  [a, b, c]

推荐答案

您可以像这样使用apply.

You can use apply, like this.

In [13]: df[df['col'].apply(lambda x: 'b' in x)]
Out[13]: 
         col
0     [a, b]
2  [a, b, c]

尽管通常将列表存储在DataFrame中有点尴尬-您可能会发现更易于使用的一些不同表示形式(列表中每个元素的列,MultiIndex等).

Although generally, storing lists in a DataFrame is a bit awkward - you might find some different representation (columns for each element in the list, MultiIndex, etc) that is easier to work with.

这篇关于如何筛选包含特定项目的列表的DataFrame列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆