dataframe筛选列名,如何筛选包含特定项目的列表的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')]

returns:

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']]})

how can I get all lists containing 'b'?

col

0 [a, b]

2 [a, b, c]

解决方案

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]

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值