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

Pandas多级索引DataFrame合并:目标格式生成方法咨询

Answers to Your Pandas DataFrame Questions

Hey there! Let's tackle your two questions step by step with practical Pandas code examples to make things clear. First, let's set up sample DataFrames x and y that match your description (same indices and columns):

import pandas as pd

# Create sample DataFrames x and y with identical indices/columns
data = {'Column1': [10, 20, 30], 'Column2': [40, 50, 60]}
x = pd.DataFrame(data, index=['RowA', 'RowB', 'RowC'])
y = pd.DataFrame({k: [v*2 for v in vals] for k, vals in data.items()}, index=['RowA', 'RowB', 'RowC'])

1. Can we directly generate the target DataFrame from x and y?

Absolutely! The exact approach depends on your target's structure, but let's assume your target has original column names as the top level and the source (x/y) as the second level in the column hierarchy. Here's a straightforward way to build it directly:

# Directly construct the target DataFrame
target_direct = pd.concat(
    [x, y], 
    axis=1, 
    keys=['x', 'y']  # Label the source of each DataFrame
).swaplevel(axis=1).sort_index(axis=1)

What this does:

  • pd.concat(..., keys=['x','y'], axis=1) stacks x and y side by side with a multi-level column index (first level: x/y, second level: original columns)
  • swaplevel(axis=1) swaps the two column levels to put original columns on top
  • sort_index(axis=1) ensures columns are grouped by their original names for readability

If your target has a different structure (e.g., multi-level rows instead of columns), you can adjust the axis parameter in concat and tweak the level swapping accordingly.


2. Can we adjust the column levels of z to get the target DataFrame?

Yes! If you already have z (your existing multi-level column DataFrame created from x and y), you can rearrange its column hierarchy to match target using Pandas' level manipulation methods.

Assuming z was created like this:

# Your existing multi-level DataFrame z
z = pd.concat([x, y], axis=1, keys=['x', 'y'])

You can transform z into target with these steps:

# Adjust z's column levels to get target
target_from_z = z.swaplevel(axis=1).sort_index(axis=1)
  • swaplevel(axis=1) swaps the order of the column levels (switches the source label and original column name)
  • sort_index(axis=1) organizes the columns so all columns from the original name are grouped together, matching typical target formatting

If your z has a different level order, you can use reorder_levels instead of swaplevel to specify the exact order you want (e.g., z.reorder_levels(['OriginalColumn', 'Source'], axis=1)).


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:58:22