我有两个数据框:
我想将这两个数据框与名称data_inputs合并在一起。这个新的数据框应该是(4760,3)。到目前为止我有这个代码:
data_inputs = pd.concat([pre_data_inputs, Diff_Course_PreCourse], axis=1)
但是data_inputs的大小现在是(4950,3)。我不知道是什么问题。如果有人能帮助我,我将不胜感激。谢谢。
好吧,如果您的索引在两种情况下都匹配,您可以使用:
pre_data_inputs.merge(Diff_Course_PreCourse, left_index=True, right_index=True)
否则,您可能希望在两个数据帧上使用reset_index()
。
正如@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