dataframe筛选列名_如何筛选包含特定项目的列表的DataFrame列

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.

Original: https://blog.csdn.net/weixin_33603823/article/details/113024458
Author: 水稻偏爱者
Title: dataframe筛选列名_如何筛选包含特定项目的列表的DataFrame列

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/752707/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球