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

如何按时间序列索引合并两个Pandas DataFrame?

Fixing DataFrame Merging Issues in Pandas

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=0 instead of axis=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 Date actually the index of one/both DataFrames instead of a column? Use FSample.columns and GMSample.columns to list all column names and confirm;
  • Did you misspell the column name? (e.g., lowercase date, or Date_ 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.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:52:25