我有一个数据帧
col0 col1 col2 col3 col4
0 1 3 6 6 0
1 0 2 8 7 3
2 0 0 4 3 4
3 4 2 2 0 4
逻辑是,如果col1不为零,则返回col1。如果col1为零,则返回col2(非零(。如果col2为零,则返回col3。我们不需要为col4 做任何事情
我的代码如下,但它只返回col1
def test(df):
if df['col1'].iloc[0] > 0:
return df['col1']
elif df['col1'].iloc[0] == 0 & df['col2'].iloc[0] > 0:
return df['col2']
elif df['col2'].iloc[0] == 0 & df['col3'].iloc[0] > 0:
return df['col3']
else:
return 0
test(new)
我试过.any((和.all((,都不起作用。另外,有没有办法让这段代码更有效率?
@ALollz思想的变体,因为查找在pandas 1.2.0:上被弃用
indices = np.argmax(df.ne(0).values, axis=1)
print(df.values[np.arange(len(df)), indices])
输出
[1 2 4 4]
更新
要排除最后一列并返回0,请执行以下操作:
indices = np.argmax(df.ne(0).iloc[:, :-1].values, axis=1)
result = np.where(df.ne(0).iloc[:, :-1].any(1), df.values[np.arange(len(df)), indices], 0)
print(result)