【问题标题】:How to merge two data frames together?如何将两个数据框合并在一起?
【发布时间】:2018-08-13 07:05:57
【问题描述】:

我有两个数据框:

  1. Pre_data_inputs 大小为 (4760,2)
  2. Diff_course_Precourse,大小为 (4760,1)。

我想将这两个数据框与名称 data_inputs 合并在一起。这个新的数据框应该是 (4760,3)。到目前为止我有这个代码:

data_inputs = pd.concat([pre_data_inputs, Diff_Course_PreCourse], axis=1)

但现在 data_inputs 的大小是 (4950,3)。 我不知道是什么问题。如果有人可以帮助我,我将不胜感激。谢谢。

【问题讨论】:

  • 两个数据帧之间的索引是否匹配,正如您在此处假设的concat?否则使用merge 合并特定列。

标签: python pandas dataframe merge concat


【解决方案1】:

如果你的索引在这两种情况下都匹配,你可以选择:

pre_data_inputs.merge(Diff_Course_PreCourse, left_index=True, right_index=True)

否则,您可能希望在两个数据帧上都使用reset_index()

【讨论】:

    【解决方案2】:

    正如@Parfait 评论的那样,您的数据帧的索引必须与concat 匹配才能按照您的描述工作。

    例如:

    d1 = pd.DataFrame(np.zeros(shape = (3,1)))
         0
    0  0.0
    1  0.0
    2  0.0
    
    d2 = pd.DataFrame(np.ones(shape = (3,2)), index = range(2,5))
         0    1
    2  1.0  1.0
    3  1.0  1.0
    4  1.0  1.0
    

    由于索引不匹配,结果数据框的行数将等于唯一索引集 (0,1,2,3,4)

    pd.concat([d1, d2], axis = 1)
         0    0    1
    0  0.0  NaN  NaN
    1  0.0  NaN  NaN
    2  0.0  1.0  1.0
    3  NaN  1.0  1.0
    4  NaN  1.0  1.0
    

    您可以在 concat 之前使用reset_index 或强制其中一个数据框使用另一个数据框的索引

    pd.concat([d1, d2.set_index(d1.index)], axis = 1)
         0    0    1
    0  0.0  1.0  1.0
    1  0.0  1.0  1.0
    2  0.0  1.0  1.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2021-10-13
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多