如何在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 1 | Set 2 | |
|---|---|---|
| 0 1 2 3 4 | 0 1 2 3 4 5 6 7 | |
| A | 1 2 2 1 1 | 1 2 2 1 1 2 2 1 |
| B | 2 1 1 2 2 | 2 1 1 2 2 1 1 2 |
| C | 2 1 1 2 2 | 1 2 2 1 1 2 2 1 |
| D | 1 2 2 1 1 | 2 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
相关产品推荐
相关产品推荐

