【问题标题】:Pandas merging 2 dataframes on their similar columns(which is the index)Pandas 在其相似列上合并 2 个数据框(即索引)
【发布时间】:2018-05-09 17:44:23
【问题描述】:

我有两个数据框,我碰巧将“timeStamp”设置为索引。 df_1.set_index('timeStamp', inplace=True)

df_1

                     value
timeStamp                 
2016-11-23 20:00:00  37.21
2016-11-23 21:00:00  37.79
2016-11-23 22:00:00  33.99
2016-11-23 23:00:00  32.66
2016-11-24 00:00:00  31.61

df_2

                     value
timeStamp                 
2016-11-23 23:00:00  32.92
2016-11-24 00:00:00  31.54
2016-11-24 01:00:00  29.14

我想制作一个数据框,在共享时间时比较这两个值。我尝试了combined_df= pd.merge(df_real, df_fc, on='timeStamp', how='inner'),得到了key error

因此,我没有将两个数据帧合并到一个索引上,而是保留了没有“timeStamp”的数据帧作为它们的索引。例如。

我用 df 代替合并

             timeStamp  value
0  2016-11-23 20:00:00  37.21
1  2016-11-23 21:00:00  37.79
2  2016-11-23 22:00:00  33.99
3  2016-11-23 23:00:00  32.66
13 2016-11-24 00:00:00  31.61

然后我能够合并并设置我的新df(如下所示)。稍后我还将索引设置为时间戳。

            timeStamp  value_x  value_y 
0  2016-11-23 23:00:00    32.66    32.92 

我的问题为什么我不能合并指定为索引的列名?我想将该合并设置为一个新的数据框...

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我相信您可以合并索引。您似乎只是使用了错误的语法。而不是指定on,您应该尝试使用left_indexright_index

    documentation for merges here

    【讨论】:

      【解决方案2】:

      您需要表明您正在合并索引:

      pd.merge(df_1, df_2, left_index=True, right_index=True, how='inner')
      

      【讨论】:

        【解决方案3】:

        DataFrame 加入/合并

        pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
                 left_index=False, right_index=False, sort=True,
                 suffixes=('_x', '_y'), copy=True, indicator=False,
                 validate=None)
        

        https://pandas.pydata.org/pandas-docs/stable/merging.html

        【讨论】:

          【解决方案4】:

          试试这个:

          df_real.merge(df_fc, on='timeStamp', how='inner')
          

          测试代码:

          import pandas as pd
          d = {'time1': ['A', 'B'], 'val1': [2, 4]}
          df = pd.DataFrame(data=d)
          df.set_index('time1')
          
          d1 = {'time1': ['A', 'B','C'], 'val1': [5, 6, 9]}
          df2 = pd.DataFrame(data=d1)
          df2.set_index('time1')
          
          df.merge(df2, on = 'time1')
          

          输出是:

              time1   val1_x  val1_y
            0    A       2      5
            1    B       4      6
          

          【讨论】:

            猜你喜欢
            • 2019-12-09
            • 1970-01-01
            • 2017-12-07
            • 1970-01-01
            • 1970-01-01
            • 2018-06-12
            • 2021-08-23
            • 1970-01-01
            • 2018-09-24
            相关资源
            最近更新 更多