如何在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 whereTruerepresents 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 returnspd.NA(swap this with0if 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
相关产品推荐
相关产品推荐

