我有一个数据框,我正在检查它是否在所有列中都是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
我希望它能回来
col1 col2 col3 test
0 None None None None
1 Y Y N Y
2 N N N N
最佳答案
你可以在里面包装另一个numpy.where
来检查null条件:
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
关于python - Pandas 检查多列的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155839/