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

为何无法基于设为索引的timeStamp列合并Pandas DataFrame?

Why pd.merge() Throws KeyError When Merging on Indexed 'timeStamp'

Great question! Let's break down exactly why this happens and how you can fix it to merge using your indexed time column.

The Root Cause

When you run df.set_index('timeStamp', inplace=True), that column is no longer part of the DataFrame's regular columns — it moves into a separate structure called the index.

The pd.merge() function's on parameter is designed to look for matching column names in both DataFrames. Since 'timeStamp' is now the index (not a column) in both df_real and df_fc, pandas can't find a column named 'timeStamp' to use for merging, hence the KeyError.

Fixes to Merge Using the Index

You have a few straightforward options to merge based on the indexed 'timeStamp' column:

  1. Use left_index and right_index parameters
    Tell pd.merge() to use the index of each DataFrame for matching instead of a column:

    merged_df = pd.merge(df_real, df_fc, left_index=True, right_index=True, how='inner')
    
  2. Reset indexes first (your original workaround, formalized)
    If you prefer sticking with the on parameter, convert the index back to a column for both DataFrames first:

    # Reset indexes to turn 'timeStamp' back into a column
    df_real_reset = df_real.reset_index()
    df_fc_reset = df_fc.reset_index()
    # Now merge using the column
    merged_df = pd.merge(df_real_reset, df_fc_reset, on='timeStamp', how='inner')
    
  3. Use DataFrame.join() (simpler for index-based merges)
    The join() method is built specifically for merging on indexes, so it's more concise here:

    merged_df = df_real.join(df_fc, how='inner')
    

Quick Note

Just double-check that the indexes of both DataFrames are the same data type (e.g., both datetime64 or both string). If one is a string and the other is a datetime, even if the values look identical, they won't match correctly. Since your workaround of resetting the column works, this is probably not an issue for you, but it's a common gotcha!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:33:27