我想使用来自两个不同数据框的列创建一个数据框。我使用的是pd.concat,但是返回的行数超过实际的行数。
尽管如果我通过首先将列堆叠在numpy数组中来创建数据框,那么我会得到预期的结果。
print(df1.shape)
print(df2.shape)
result1 = pd.concat([df1, df2], axis=1)
result2 = pd.Dataframe(np.column_stack([df1.user_id, df2.prob]),
columns = ["user_id", "prob"])
print(result1.shape)
print(result2.shape)
输出:
(221471, 1)
(221471, 1)
(221515, 2)
(221471, 2)
有人可以帮我理解为什么concat返回更多行吗?
答案 0 :(得分:0)
实际上,评论所指向的链接答案并不完整。您需要在concat操作之前使用:
df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)
答案 1 :(得分:0)
重置索引后使用以下内容。
pd.merge(df1, df2, left_index=True, right_index=True)