2017-10-12 46 views
3

我試圖刪除df中存在於lst中的列表中的值的行。刪除另一個列表中存在的列表中的數據幀的行

我知道使用單數字符串使用df[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. 
+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 s的列表,因此需要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]] 
+0

我的救世主!再次感謝:-) – LearningToPython

+0

我遇到了一個小問題。當'lst'已經包含某些東西時,您建議的代碼似乎可以正常工作。 ''f''和''a''。但是,如果我向'lst'追加一些東西,然後運行代碼,它似乎不工作,有什麼想法? – LearningToPython

+0

嗯,它應該工作。不幸的是,現在我要睡覺,但明天我可以檢查。你的問題有可能改變問題嗎?謝謝。 – jezrael

相關問題