首页 > 解决方案 > 在 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功能不起作用?

标签: pandasdataframepd

解决方案


为什么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 in some_set_or_list[0], if col1[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)

推荐阅读