简体   繁体   中英

Is it possible to filter Pandas DataFrame column if column is a list?

import pandas as pd

dafr = pd.DataFrame({'a': [1,2,3], 'b': [[1,2,3],[2,3,4],[3,4,5]]})

I try to do something like:

dafr[dafr['b'].isin(2)]

which should return rows that has lists: [1,2,3] & [2,3,4].

I wonder if this is possible?

isin returns whether the column value is in what you pass. You want to check if what you pass is in the column value.

As far as I know there is no direct shortcut for this, but you can do it using map :

>>> dafr[dafr.b.map(lambda x: 2 in x)]
    a          b
0  1  [1, 2, 3]
1  2  [2, 3, 4]
dafr[dafr['b'].apply(lambda x: 2 in x)]

如果将b存储为元组列而不是列表列,则afr[dafr['b'].apply(lambda x: 2 in x)]将执行得非常快。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM