返回panda df中的最后一个非零值

2024-04-26 11:04:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧

    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。如果列1为零,则返回列2(非零)。如果col 2为零,则返回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(),它也不起作用。另外,是否有任何方法可以使这段代码更高效


Tags: 数据代码testdfreturndefcol逻辑
1条回答
网友
1楼 · 发布于 2024-04-26 11:04:28

@ALollz idea的一个变体,因为熊猫1.2.0不推荐使用lookup

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)

相关问题 更多 >