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

如何实现Pandas DataFrame列累计求和且不延续至末尾零值

Cumulative Sum on Pandas DataFrame (Excluding Trailing All-Zero Rows)

Got it, let's break this down. You need to calculate a cumulative sum for your DataFrame, but only apply it to the rows before the trailing continuous all-zero section—leaving those final zero rows exactly as they are. Here's a straightforward, robust solution:

Step 1: Set Up Your Example DataFrame

First, let's recreate the sample DataFrame you provided to test our solution:

import pandas as pd

# Sample data matching your example
data = {
    'A': [1, 5, 10, 10, 0, 5, 0, 0, 0],
    'B': [2, 0, 0, 1, 1, 2, 0, 0, 0]
}
df = pd.DataFrame(data, index=range(1, 10))

Step 2: Identify the Last Non-All-Zero Row

We need to find the boundary where the trailing zeros start. This involves:

  1. Checking which rows are entirely made of zeros
  2. Grabbing the index of the last row that isn't all zeros
# Create a boolean Series marking rows where all columns are 0
all_zero_rows = df.eq(0).all(axis=1)

# Check if there are any non-zero rows (handles edge case of all-zero DataFrames)
if (~all_zero_rows).any():
    # Get the index of the last row that isn't all zeros
    last_valid_idx = all_zero_rows[~all_zero_rows].index[-1]
else:
    # If the entire DataFrame is zeros, we can skip processing
    result = df.copy()

Step 3: Apply Cumulative Sum to Valid Rows

Now we'll apply cumsum() only to the rows up to that last valid index, leaving the trailing zeros untouched:

# Make a copy of the original DataFrame to avoid modifying it directly
result = df.copy()

# Apply cumulative sum to all rows up to (and including) the last non-all-zero row
if (~all_zero_rows).any():
    result.loc[:last_valid_idx] = result.loc[:last_valid_idx].cumsum()

# Print the result to verify
print(result)

Output (Matches Your Expected Result):

A  B
1   1  2
2   6  2
3  16  2
4  26  3
5  26  4
6  31  6
7   0  0
8   0  0
9   0  0

Key Notes:

  • Edge Case Handling: The code checks if there are any non-zero rows first—so if your entire DataFrame is zeros, it just returns the original data without errors.
  • Non-Contiguous Zeros: This solution only ignores the trailing continuous all-zero rows. If there are zeros in the middle (like rows 2-3 in your example), they still get included in the cumulative sum, which is exactly what you want.

内容的提问来源于stack exchange,提问作者ArchieTiger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:26:29