2016-09-27 70 views
2

我在過濾數據類型爲列表的列上的pandas數據框時遇到了一些問題(我們稱之爲column_1)。具體而言,我只想返回行,以便column_1和另一個預定列表的交集不爲空。但是,當我嘗試將邏輯放在.where,function的參數中時,我總是會得到錯誤。以下是我的嘗試,並返回錯誤。如何在列數據類型爲列表時過濾pandas數據框

  • Attemping測試單個元素是否是列表中:

    table[element in table['column_1']] 返回錯誤...... KeyError: False

  • 試圖將名單與所有的名單在數據幀的行中:

    table[[349569] == table.column_1]返回錯誤Arrays were different lengths: 23041 vs 1

我試圖讓這兩個中間步驟下來,然後我測試兩個列表的交集。

感謝您花時間閱讀我的問題!

回答

0

考慮pd.Seriess

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每個元素轉換爲一組,並intersectiontest

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