如何将单层索引DataFrame添加到多层索引DataFrame(Pandas/Python)
Let's walk through how to add your single-index DataFrame into the specific Date='20170120' group of your multi-index DataFrame. First, let's fix the data formatting from your example to create valid Pandas objects, since the original input was a bit messy.
Step 1: Reconstruct the Original DataFrames
First, let's build the multi-index DataFrame and the single-index DataFrame as per your description:
import pandas as pd # Original multi-index DataFrame multi_df = pd.DataFrame( data={ 'Name': ['a', 'b'], 'Buying_Date': ['20170101', '20180101'], 'Buying_Price': [5, 6], 'Buying_Qty': [7, 8] }, index=pd.MultiIndex.from_tuples( [('20140117', 'none'), ('20170120', 'none')], names=['Date', 'Code'] ) ) # Single-index DataFrame to add single_df = pd.DataFrame( data={ 'Name': ['abcd', 'efgh'], 'Code': ['af', 'bf'], 'Buying_Date': ['20170101', '20180101'], 'Buying_Price': [5, 6], 'Buying_Qty': [7, 8] } )
Step 2: Add the Target Multi-Index Level to the Single-Index DataFrame
We need to assign the Date='20170120' value as the top-level index for all rows in the single-index DataFrame, then convert it to a multi-index matching the original structure:
# Add the 'Date' level to the single DataFrame single_df_with_multi = single_df.set_index([pd.Series(['20170120']*len(single_df), name='Date'), 'Code'])
Step 3: Combine the Two DataFrames
Use pd.concat() to merge the original multi-index DataFrame with the modified single-index DataFrame. This will append the new rows under the 20170120 Date group:
# Concatenate the DataFrames result_df = pd.concat([multi_df, single_df_with_multi])
Step 4: Verify the Result
If you print result_df, you'll get exactly the structure you wanted:
print(result_df)
Output:
Name Buying_Date Buying_Price Buying_Qty Date Code 20140117 none a 20170101 5 7 20170120 none b 20180101 6 8 af abcd 20170101 5 7 bf efgh 20180101 6 8
Key Notes
- Make sure the column names of both DataFrames match exactly (they do in your example, which is good!).
- When setting the multi-index for the single DataFrame, we explicitly set the index names (
DateandCode) to match the original multi-index, soconcatcan align them correctly. - If you want to sort the index after concatenation, you can use
result_df.sort_index()to keep the groups organized.
内容的提问来源于stack exchange,提问作者Vince

