2017-10-13 105 views
0

這裏的第一個問題,所以它可能會有點混亂。如果在pandas中另一列的條目爲nan,那麼將數據框的條目追加到列表中?

所以我有這樣一個數據幀:

  A   B 
1:  'a'  'aa' 
2:  'b'  NaN 
3:  'c'  NaN 
4:  'd'  'dd' 

,我已經創建了一個清單:

lst=[] 

我想,如果價值在column A附加價值這一list在這種情況下,Column BNaN,又名['b','c']

迴圈肯定有效,但有沒有一種優雅的方式(例如使用lambda)來做到這一點?

謝謝!

回答

3

使用boolean indexing用於過濾和str.strip用於刪除'

lst = df.loc[df['B'].isnull(), 'A'].tolist() 
print (lst) 
["'b'", "'c'"] 

lst = df.loc[df['B'].isnull(), 'A'].str.strip("'").tolist() 
print (lst) 
['b', 'c'] 

詳情:

print (df['B'].isnull()) 
1: False 
2:  True 
3:  True 
4: False 
Name: B, dtype: bool 

print (df.loc[df['B'].isnull(), 'A']) 
2: 'b' 
3: 'c' 
Name: A, dtype: object 

print (df.loc[df['B'].isnull(), 'A'].str.strip("'")) 
2: b 
3: c 
Name: A, dtype: object 
相關問題