pandas - 在 Dataframe 中选择一列的值在另一列表列中的行
问题描述
我正在尝试以下
df = pd.DataFrame({'col1': [1,2,3], 'col2': [[1,2], [3,4], [3,2]]})
df
col1 col2
0 1 [1, 2]
1 2 [3, 4]
2 3 [3, 2]
我想选择col1
值在col2
列表中的行
df[df.col1.isin(df.col2)]
Empty DataFrame
Columns: [col1, col2]
Index: []
但我得到了空的df。为什么isin
功能不起作用?
解决方案
为什么
isin
功能不起作用?
Series.isin
接受一个集合或列表。你打电话时:
df.col1.isin(some_set_or_list)
- 它只是测试 的每个值
col1
是否在整个some_set_or_list
中,在这种情况下是[[1,2],[3,4],[3,2]]
。 - 它不测试if
col1[0]
is insome_set_or_list[0]
, ifcol1[1]
is insome_set_or_list[1]
等。事实上some_set_or_list
,它的长度可能与 . 完全不同col1
。
例如,如果col1
' 的第一个值[3,4]
改为:
df = pd.DataFrame({'col1': [[3,4],2,3], 'col2': [[1,2], [3,4], [3,2]]})
# col1 col2
# 0 [3, 4] [1, 2]
# 1 2 [3, 4]
# 2 3 [3, 2]
isin
会给你True
第一行,因为它是[3,4]
一个整体(不是元素方面):col2
df.col1.isin(df.col2)
# 0 True
# 1 False
# 2 False
# Name: col1, dtype: bool
您实际上要做的是逐行测试,这就是Rob 的回答:
df.apply(lambda row: row.col1 in row.col2, axis=1)
推荐阅读
- r - 基于单词列表的分类 R
- arrays - 如何在 TypeScript 中定义具有不同类型项目和特定顺序的数组类型?
- java - PMD CallSuperInConstructor 的原因是什么?
- javascript - 循环遍历层次结构树并从中创建一个 REACT UI
- ios - 弹出日期选择器以设置日期
- aws-lambda - 使用 jenkins 和 aws cli 发布 aws lambda 版本
- c# - 在二维数组中分配值不起作用 - 交换索引
- javascript - 未处理的“错误”事件。(TypeError:无法读取 null 的属性“标题”)
- javascript - 这个 RGB 到 HSV 颜色转换方程我做错了什么?
- r - 两列合并为一但合并再次创建两列