在 Pandas DataFrame 的每一列中查找第一个非零值

Kon*_*tin 9 python dataframe pandas

在 DataFrame 的每一列(从上到下)中获取第一个非零元素的值和索引的 pandoric 方法是什么?

import pandas as pd

df = pd.DataFrame([[0, 0, 0],
                   [0, 10, 0],
                   [4, 0, 0],
                   [1, 2, 3]],
                  columns=['first', 'second', 'third'])

print(df.head())

#    first  second  third
# 0      0       0      0
# 1      0      10      0
# 2      4       0      0
# 3      1       2      3
Run Code Online (Sandbox Code Playgroud)

我想达到的目标:

#        value  pos
# first      4    2
# second    10    1
# third      1    3
Run Code Online (Sandbox Code Playgroud)

piR*_*red 13

您正在寻找idxmax哪个可以为您提供最大值的第一个位置。但是,您需要找到“不等于零”的最大值

df.ne(0).idxmax()

first     2
second    1
third     3
dtype: int64
Run Code Online (Sandbox Code Playgroud)

我们可以将它与lookupassign

df.ne(0).idxmax().to_frame('pos').assign(val=lambda d: df.lookup(d.pos, d.index))

        pos  val
first     2    4
second    1   10
third     3    3
Run Code Online (Sandbox Code Playgroud)

相同的答案包装略有不同。

m = df.ne(0).idxmax()
pd.DataFrame(dict(pos=m, val=df.lookup(m, m.index)))

        pos  val
first     2    4
second    1   10
third     3    3
Run Code Online (Sandbox Code Playgroud)