如何按时间序列索引合并两个Pandas DataFrame?
Hey Joseph, let's break down your two merging problems and get you the result you want:
1. Why pd.concat([FSample, GMSample], axis=1) is stacking rows instead of columns?
This is a bit unexpected because axis=1 is supposed to merge side-by-side (column-wise)—row stacking is what axis=0 does. Here are the two most likely causes:
- You might have accidentally typed
axis=0instead ofaxis=1(easy typo!); - Your two DataFrames have no overlapping indices, so when you try to merge side-by-side, pandas fills missing rows with NaNs. This can make the result look like the data is stacked vertically, even though it's actually horizontal.
Fix for concat:
First, make sure your Date field is set as the index for both DataFrames (so pandas can align rows correctly):
# If 'Date' is a column in both DataFrames, set it as the index FSample = FSample.set_index('Date') GMSample = GMSample.set_index('Date') # Now do the column-wise concat result = pd.concat([FSample, GMSample], axis=1)
This will align rows by the Date index and merge columns side-by-side.
2. Why pd.merge(..., on='Date') throws a 'Date' KeyError?
This error means one or both of your DataFrames don't have a column named 'Date'. Let's check two things:
- Is
Dateactually the index of one/both DataFrames instead of a column? UseFSample.columnsandGMSample.columnsto list all column names and confirm; - Did you misspell the column name? (e.g., lowercase
date, orDate_with a suffix)
Fix for merge:
Case 1: Date is the index (not a column)
Use left_index=True and right_index=True to merge on the index instead of a column:
# Inner join using the Date index result = pd.merge(FSample, GMSample, how='inner', left_index=True, right_index=True)
Case 2: Date is a column but misnamed
Fix the column name first, then merge:
# Example: if GMSample uses 'date' instead of 'Date' GMSample.rename(columns={'date': 'Date'}, inplace=True) # Now merge on the corrected column name result = pd.merge(FSample, GMSample, how='inner', on='Date')
Quick Debug Tip
To avoid confusion, print out basic info about your DataFrames first:
print("FSample Columns:", FSample.columns.tolist()) print("FSample Index Name:", FSample.index.name) print("\nGMSample Columns:", GMSample.columns.tolist()) print("GMSample Index Name:", GMSample.index.name)
This will instantly tell you if Date is a column or index, and if there are spelling mismatches.
内容的提问来源于stack exchange,提问作者Joseph U.

