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

Pandas透视表cumsum():如何跨列传递非NaN值?

Answer

Absolutely! You can easily propagate the previous non-NaN value across columns in the same row after performing a cumsum() on your Pandas pivot table. This is exactly what the ffill() (forward fill) method was designed for—let’s break down how to implement it.

Step 1: Reproduce the Scenario

First, let’s create a sample pivot table that mirrors your situation (with NaNs after cumsum()):

import pandas as pd

# Sample data matching your use case
data = {
    'Group': ['X', 'X', 'X', 'Y', 'Y'],
    'Period': ['P1', 'P3', 'P4', 'P2', 'P4'],
    'Value': [1, 0, 0, 1, 0]
}

df = pd.DataFrame(data)

# Create pivot table without filling missing periods (so NaNs exist)
pivot = df.pivot_table(index='Group', columns='Period', values='Value')

# Calculate cumulative sum across columns
pivot_cumsum = pivot.cumsum(axis=1)
print("Original cumsum result with NaNs:")
print(pivot_cumsum)

This will output something like:

Period   P1   P2   P3   P4
Group
X      1.0  NaN  1.0  1.0
Y      NaN  1.0  NaN  1.0

Notice the NaNs in row X (P2) and row Y (P1, P3)—these are the positions you want to fill with the previous non-NaN value from the same row.

Step 2: Forward Fill to Propagate Values

Use ffill(axis=1) to fill NaNs with the nearest non-NaN value from the left (same row, previous column):

# Propagate previous values across columns
filled_pivot = pivot_cumsum.ffill(axis=1)
print("\nFilled result with propagated values:")
print(filled_pivot)

The output now becomes:

Period   P1   P2   P3   P4
Group
X      1.0  1.0  1.0  1.0
Y      NaN  1.0  1.0  1.0

Step 3: Handle Leading NaNs (Optional)

If you have leading NaNs (like row Y’s P1), you can fill those with a default value (e.g., 0) or use bfill(axis=1) to propagate the first non-NaN value backward:

# Fill leading NaNs with 0
final_pivot = filled_pivot.fillna(0)
print("\nFinal result with leading NaNs filled:")
print(final_pivot)

Which gives:

Period   P1   P2   P3   P4
Group
X      1.0  1.0  1.0  1.0
Y      0.0  1.0  1.0  1.0

Key Notes

  • ffill(axis=1) works by iterating through each row from left to right, replacing NaNs with the last valid value it encountered. This perfectly matches your requirement to pass the known value from the previous column to subsequent NaNs in the same row.
  • If you need to fill from right to left instead, use bfill(axis=1).

Hope this helps you get the exact pivot table output you’re looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:41:17