2016-12-28 34 views
1

如何在熊貓中做條件替換?如何在帶有空閥門的熊貓/ python中做條件語句

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]]) 

在的R - 覺得這個代碼是很容易理解:

library(dplyr) 
df = df %>% 
mutate( # mutate means create new column for non-r people 
my_new_column = ifelse(is.na(the_2nd_column)==TRUE & is.na(the_3rd_column)==TRUE, ' abc', 'cuz') 

我怎麼在大熊貓做到這一點 - 與語法可能愚蠢的問題,但我聽說np.where是等效的if else R中......

df['new_column'] = np.where(np.nan(....help here with a conditional....)) 

回答

4

np.where這樣

df['new_column'] = np.where(df[1].isnull() & df[2].isnull(), 'abc', 'cuz') 
print(df) 

或更多numpy的

df['new_column'] = \ 
    np.where(np.isnan(df[1].values) & np.isnan(df[2].values), 'abc', 'cuz') 


    0 1 2 new_column 
0 1.0 2.0 3.0  cuz 
1 4.0 NaN NaN  abc 
2 NaN NaN 9.0  cuz 

定時

enter image description here

+0

您能否把時間按照升序排列?中間有一個208us,它應該上升。 :D:P呵呵 – MYGz

+0

謝謝你這個作品 - 特別是空.....版本,但是我有一個問題,如果你不介意。如果我是兩個追加兩個數據集,並且1個數據集中存在1個數據集,而另一個數據集中不存在 - 那麼當nan版本工作時,nan版本會產生錯誤消息。看起來,null對於錯誤更加健壯。 – runningbirds

+0

也許有更好的基準數據集? – Zero

1

使用更快的np.where

In [279]: df['new'] = np.where(df[[1, 2]].isnull().all(axis=1), 'abc', 'cuz') 

In [280]: df 
Out[280]: 
    0 1 2 new 
0 1.0 2.0 3.0 cuz 
1 4.0 NaN NaN abc 
2 NaN NaN 9.0 cuz 
+0

謝謝你這個作品 – runningbirds