2017-10-18 161 views
1

我有一個熊貓數據幀這樣的條件邏輯新列:大熊貓基礎上添加許多其他列

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

我想添加一個新列,如果在列值1至4 a

結果會是這樣:

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

的邏輯是: 如果在任何列的值1至4是a然後柱是a否則它b

我可以定義一個函數,並做手工每一列,如:

def some_function(row); 
    if row['aa']=='a' or row['bb']=='a' or row['cc']=='a' or row[dd]=='a': 
     return 'a' 
    return 'b' 

但是我正在尋找的是可以遍及n數列的解決方案。

感謝任何幫助!

+0

也許你可以使用'df.iloc [:,:4] .min(1 )'? – Zero

回答

1

使用numpy.where與條件由eq(==)與any用於檢查至少一個True每行創建:

cols = ['aa','bb','cc', 'dd'] 
df['ff'] = np.where(df[cols].eq('a').any(1), 'a', 'b') 
print (df) 
    aa bb cc dd ee ff 
0 a a b b foo a 
1 a b a a foo a 
2 b a a a bar a 
3 b b b b bar b 

詳細信息:

print (df[cols].eq('a')) 
     aa  bb  cc 
0 True True False 
1 True False True 
2 False True True 
3 False False False 

print (df[cols].eq('a').any(1)) 
0  True 
1  True 
2  True 
3 False 
dtype: bool 

如果需要自定義函數:

def some_function(row): 
    if row[cols].eq('a').any(): 
     return 'a' 
    return 'b' 

df['ff'] = df.apply(some_function, 1) 
print (df) 
    aa bb cc dd ee ff 
0 a a b b foo a 
1 a b a a foo a 
2 b a a a bar a 
3 b b b b bar b 
+0

真棒謝謝@jezrael! – Kvothe

+0

歡迎您和美好的一天! – jezrael