我有以下数据帧:
index | jan | feb | marc | april |
---|---|---|---|---|
One | 1 | 7 | 0 | 0 |
two | 0 | 8 | 7 | 0 |
three | 0 | 0 | 0 | 1 |
我想要获取每行最后一个非零值后面的零的数量。因此输出应该如下所示:
索引 | 数字 |
---|---|
一 | 2 |
二 | 1 |
三 | 0 |
import pandas as pd
# Dataframe
data = {
'jan': [1, 0, 0],
'feb': [7, 8, 0],
'marc': [0, 7, 0],
'april': [0, 0, 1]
}
df = pd.DataFrame(data, index=['One', 'two', 'three'])
# Calculate the number of zeros after the last non-zero value per index/row
num_zeros = df.ne(0).iloc[:, ::-1].cumsum(axis=1).eq(0).sum(axis=1)
# Result dataframe
result = pd.DataFrame({'num': num_zeros}, index=df.index)
print("DataFrame:")
print(df)
print("\nResult:")
print(result)
计算零的数量 (df.ne(0).iloc[:, ::-1].cumsum(axis=1).eq(0).sum(axis=1)):
输出:
DataFrame:
jan feb marc april
One 1 7 0 0
two 0 8 7 0
three 0 0 0 1
Result:
num
One 2
two 1
three 0
与@BrJ的逻辑类似,但我认为更加直接。
使用反转的cummin
将所有False
之前的True
设置为False
,然后使用sum
:
out = (df.loc[:,::-1].eq(0)
.cummin(axis=1).sum(axis=1)
.to_frame('num')
)
输出:
num
One 2
two 1
three 0
中级:
# boolean mask (0s are True)
jan feb marc april
One False False True True
two True False False True
three True True True False
# after reversed cummin (and reversed again for clarity)
# all True that preceded a False are now False
jan feb marc april
One False False True True
two False False False True
three False False False False