删除另一个列表中的列表中的值数据帧行

时间:2017-10-12 17:15:51

标签: python python-2.7 pandas

我正在尝试删除dflstdf[df[x].isin(y)]内的列表中的值行。

我知道将dataframe用于单数字符串,但我不确定如何调整相同的方法来处理lst = ['f','a'] 中的列表。

df

Column1 Out1 0 ['x', 'y'] a 1 ['a', 'b'] i 2 ['c', 'd'] o 3 ['e', 'f'] u etc.

Pandas

我试图使用列表理解但它似乎与df = df[[i for x in list for i in df['Column1']]]

不一样
TypeError: unhashable type: 'list'

错误:

lst

我的 预期输出 将如下所示;删除包含列表的行包含 Column1 Out1 0 ['x', 'y'] a 1 ['c', 'd'] o etc. 中的值:

uninitialized constant Reusable

1 个答案:

答案 0 :(得分:2)

您可以将转换值用于set,然后使用&,以反转掩码使用~

df = pd.DataFrame({'Column1':[['x','y'], ['a','b'], ['c','d'],['e','f']],
                   'Out1':list('aiou')})

lst = ['f','a']
df1 = df[~(df['Column1'].apply(set) & set(lst))]
print (df1)
  Column1 Out1
0  [x, y]    a
2  [c, d]    o

nested list comprehension的解决方案 - 获取boolean的列表,因此需要all检查所有值是否为True

df1 =df[[all([x not in lst for x in i]) for i in df['Column1']]]
print (df1)
  Column1 Out1
0  [x, y]    a
2  [c, d]    o
print ([[x not in lst for x in i] for i in df['Column1']])
[[True, True], [False, True], [True, True], [True, False]]