我在过滤数据类型为列表的列(我们称之为 column_1)上的 pandas 数据框时遇到了一些问题。具体来说,我只想返回 column_1 和另一个预定列表的交集不为空的行。但是,当我尝试将逻辑放在 .where 函数的参数中时,我总是会出错。以下是我的尝试,并返回了错误。
尝试测试单个元素是否在列表中:
表[表中的元素['column_1']]
返回错误...KeyError: False
尝试将列表与数据框行中的所有列表进行比较:
table[[349569] == table.column_1]
返回错误Arrays were different lengths: 23041 vs 1
在测试两个列表的交集之前,我试图降低这两个中间步骤。
感谢您花时间阅读我的问题!
最佳答案
考虑 pd.Series
s
s = pd.Series([[1, 2, 3], list('abcd'), [9, 8, 3], ['a', 4]])
print(s)
0 [1, 2, 3]
1 [a, b, c, d]
2 [9, 8, 3]
3 [a, 4]
dtype: object
和一个测试列表test
test = ['b', 3, 4]
申请lambda
转换 s
的每个元素的函数到一组和intersection
与 test
print(s.apply(lambda x: list(set(x).intersection(test))))
0 [3]
1 [b]
2 [3]
3 [4]
dtype: object
要将其用作掩码,请使用 bool
而不是 list
s.apply(lambda x: bool(set(x).intersection(test)))
0 True
1 True
2 True
3 True
dtype: bool
关于list - 当列数据类型为列表时如何过滤 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39729292/