You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DataFrame各列中查找最后一个非零元素

How to Find the Last Non-Zero Element in Each DataFrame Column

Got it, let's solve this problem. You want to get the last occurrence of a non-zero value for every column in your pandas DataFrame. Here's a straightforward way to do it using pandas' apply function with a custom lambda.

First, let's use your sample input to demonstrate:

Sample Input DataFrame

import pandas as pd

df = pd.DataFrame({
    'A': [0, 0, 9, 10, 0, 0],
    'B': [1, 2, 0, 0, 0, 0]
})

Solution Code

# Calculate last non-zero per column
last_non_zero = df.apply(lambda col: col[col != 0].iloc[-1] if any(col != 0) else pd.NA)

# Convert to a transposed DataFrame for clean output matching your expected format
result = pd.DataFrame(last_non_zero).T
print(result)

Output

A  B
0  10  2

How This Works

Let's break down the lambda function step by step:

  • col != 0: Creates a boolean mask where True represents non-zero values in the column.
  • col[col != 0]: Filters the column to keep only the non-zero values (ignoring all zeros).
  • iloc[-1]: Selects the last element from the filtered non-zero values—this is our target value.
  • if any(col !=0) else pd.NA: Handles columns with all zeros gracefully. It returns pd.NA (swap this with 0 if you want a default numeric value instead of NA).

If you don't need the result as a DataFrame and just want a concise Series, you can skip the pd.DataFrame(last_non_zero).T line—last_non_zero itself will give you a Series with column names as the index and the last non-zero values as the values.


内容的提问来源于stack exchange,提问作者fareed khan normal dist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:23:20