2017-10-18 129 views
1

我有一個熊貓數據幀這樣的條件邏輯:大熊貓添加新列基於缺失值

aa bb cc dd ee 
a a b b foo 
a b a a foo 
b nan a a bar 
b b b b bar 

我要像創建新列df['ff']

aa bb cc dd ee ff 
a a b b foo c 
a b a a foo c 
a nan a a bar d 
a b b b bar c 

的邏輯是:我的答案應該是這樣的:

df['ff'] = df.apply(lambda x: x['bb'].isnull(),axis=1) & (x['aa']=='a')

,但我得到了如下的錯誤:

("'str' object has no attribute 'isnull'", 'occurred at index 0')

回答

2

我會使用以下方法矢量:

In [47]: df['ff'] = np.where(df['bb'].notnull() & df['aa'].eq('a'), 'c', 'd') 

In [48]: df 
Out[48]: 
    aa bb cc dd ee ff 
0 a a b b foo c 
1 a b a a foo c 
2 b NaN a a bar d 
3 b b b b bar d