Pandas多级索引DataFrame合并:目标格式生成方法咨询
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)stacksxandyside 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 topsort_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

