2017-07-18 4 views
1

データフレームがあり、すべての列にYかどうかを確認しています。それ以外の場合はNを返します。また、行のすべての列がNullを返す場合はNULLを返します。パンダ条件の複数の列を確認

di = {'col1': [None, 'Y', 'N'], 'col2': [None, 'Y', 'N'], 'col3': [None, 'N', 'N']} 
df = pd.Dataframe(di) 
df['test'] = pd.np.where(df[['col1', 'col2', 'col3']].eq('Y').any(1, skipna=True), 'Y', 'N') 

このリターン:

col1 col2 col3 test 
0 None None None N 
1  Y  Y  N Y 
2  N  N  N N 

そして私はあなたがnullの状態を確認するために、別のnumpy.where内部をラップすることができ、それは

col1 col2 col3 test 
0 None None None None 
1  Y  Y  N Y 
2  N  N  N N 

答えて

2

を返したい:

df['test'] = pd.np.where(df[['col1', 'col2', 'col3']].eq('Y').any(1, skipna=True), 'Y', 
      pd.np.where(df[['col1', 'col2', 'col3']].isnull().all(1), None, 'N')) 

df 
# col1 col2 col3 test 
#0 None None None None 
#1  Y  Y  N  Y 
#2  N  N  N  N 
1

ただ、これを追加最後の行、

di = {'col1': [None, 'Y', 'N'], 'col2': [None, 'Y', 'N'], 'col3': [None, 'N', 'N']} 
df = pd.DataFrame(di) 
df['test'] = pd.np.where(df[['col1', 'col2', 'col3']].eq('Y').any(1, skipna=True), 'Y', 'N') 
df['test'] = pd.np.where(df[['col1', 'col2', 'col3']].isnull().all(1, skipna=True), None, df['test'])