pandas - 如果row [i]在Dataframe的行[j]中,则选择行

时间:2014-09-21 13:55:41

标签: python pandas

我有以下Dataframe

id B C D
1  1 1 [1,2,3]
2  2 1 [1,2,3]
3  0 1 [1,2,3]
4  1 1 [0,1]
5  2 1 [0,1]

每行的列D是一个列表。如何选择行以形成新的Dataframe,以便每行满足:B in D = True

例如,上述df的结果将变为:

id B C D
1  1 1 [1,2,3]
2  2 1 [1,2,3]
4  1 1 [0,1]

我尝试了df[df['B'] in df['D']],它给了我错误:TypeError: 'Series' objects are mutable, thus they cannot be hashed

1 个答案:

答案 0 :(得分:2)

您可以使用apply检查每一行是否满足条件,并使用生成的布尔系列进行切片:

import pandas as pd
df = pd.DataFrame( {'id':[1,2,3,4,5], 'B':[1,2,0,1,2], 'C' : [1,1,1,1,1], 'D':[[1,2,3], [1,2,3], [1,2,3], [0,1],[0,1]]})
print df[df.apply(lambda x: x['B'] in x['D'], axis=1)]

输出:

   B  C          D  id
0  1  1  [1, 2, 3]   1
1  2  1  [1, 2, 3]   2
3  1  1     [0, 1]   4

这是基于列D在行之间不相同的假设;否则,应优先考虑基于isin的解决方案,因为它更有效。