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

如何在Pandas中按MultiIndex与前置值交替替换数据?

Solution for Alternating Values in MultiIndex Column Groups

Got it, let's work through this problem step by step. You want to keep the first column's value in each MultiIndex group (Set 1/Set 2), then alternate between 1 and 2 in pairs for the remaining columns—all based on that initial row value. Here's a clean, scalable way to make this happen:

Step 1: Define a Group Processing Function

First, we'll create a function that takes a single column group (like all columns under "Set 1") and transforms each row to match your desired pattern:

def process_group(group):
    # Loop through each row in the current group
    for index, row in group.iterrows():
        first_val = row.iloc[0]
        # Set up the repeating pattern based on the first value of the row
        if first_val == 1:
            # Pattern: start with 1, then two 2s, two 1s, repeat
            base_pattern = [1, 2, 2, 1, 1]
        else:
            # Pattern: start with 2, then two 1s, two 2s, repeat
            base_pattern = [2, 1, 1, 2, 2]
        # Generate a sequence long enough to cover all columns in the group
        total_cols = len(row)
        repeated_pattern = (base_pattern * ((total_cols // len(base_pattern)) + 1))[:total_cols]
        # Replace the original row with our custom pattern
        group.loc[index] = repeated_pattern
    return group

Step 2: Apply the Function to Each MultiIndex Group

We'll use pandas' groupby on the column MultiIndex's first level (the "Set X" labels) to apply our function to each group:

# Process each column group and get the transformed DataFrame
df_processed = df.groupby(level=0, axis=1).apply(process_group)

Verify the Result

If you print df_processed, you'll see exactly the output you're looking for:

Set 1Set 2
0 1 2 3 40 1 2 3 4 5 6 7
A1 2 2 1 11 2 2 1 1 2 2 1
B2 1 1 2 22 1 1 2 2 1 1 2
C2 1 1 2 21 2 2 1 1 2 2 1
D1 2 2 1 12 1 1 2 2 1 1 2

Quick Notes

  • This solution works for groups of any column length, not just the 5 and 8 columns in your example—it repeats the base pattern as needed to fit.
  • If your data ever has initial values other than 1 or 2, you can easily add extra conditionals to handle those edge cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:33:10