2017-02-16 27 views
2

我有一個熊貓數據框,其中的一列是列表。請看下面:熊貓數據框架中的成員測試列

>>> a.head 
    C1 C2 
0 23 [2,4,5,8,1] 
1 24 [1,2] 
2 15 [-2] 
3 19 [1,3,4,5,6,7,8,9,0] 

我想找到一個在C2中包含6行並返回C1中的值。我以爲像

b = a["C1"][(6 in a["C2"])] 
return(int(b)) 

但它是行不通的。 謝謝。

回答

3

我想你需要applyin測試值在list創建boolean mask

print (a.C2.apply(lambda x: 6 in x)) 
0 False 
1 False 
2 False 
3  True 
Name: C2, dtype: bool 

然後通過maskboolean indexing使用loc的選擇:

b = a.loc[a.C2.apply(lambda x: 6 in x), 'C1'] 
print (b) 
3 19 
Name: C1, dtype: int64 

最後,如果需要的標量輸出轉換到numpy array,並通過[]選擇第一個值:

print (b.values) 
[19] 

print (b.values[0]) 
19 

或者使用iatiloc

print (b.iat[0]) 
19 

print (b.iloc[0]) 
19