[英]How to merge two pandas dataframes on index but fill missing values
I have two dataframes我有两个数据框
df
x
0 1
1 1
2 1
3 1
4 1
df1
y
1 1
3 1
And I want to merge them on the index, but still keep the indexes that aren't present in df1
.我想将它们合并到索引上,但仍保留
df1
中不存在的索引。 This is my desired output这是我想要的 output
x y
0 1 0
1 1 1
2 1 0
3 1 1
4 1 0
I have tried merging on index, like this我试过合并索引,像这样
pd.merge(df, df1s, left_index=True, right_index=True)
But that gets rid of the index values not in df1
.但这摆脱了不在
df1
中的索引值。 For example:例如:
x y
1 1 1
3 1 1
This is not what I want.这不是我想要的。 I have tried both
outer
and inner
join, to no avail.我尝试了
outer
和inner
连接,但无济于事。 I have also tried reading through other pandas merge questions, but can't seem to figure out my specific case here.我也尝试过阅读其他 pandas 合并问题,但似乎无法在这里弄清楚我的具体情况。 Apologies if the merge questions are redundant, but again, I cannot figure out how to merge the way I would like in this certain scenario.
如果合并问题是多余的,我深表歉意,但同样,我无法弄清楚如何在这种特定情况下以我想要的方式合并。 Thanks!
谢谢!
Try to concatenate on rows and fill NaNs with 0尝试连接行并用 0 填充 NaN
pd.concat([df,df1], axis=1).fillna(0)
x y
0 1 0.0
1 1 1.0
2 1 0.0
3 1 1.0
4 1 0.0
No need for any complicated merging, you can just copy the column over directly, fill the NaNs, and set the dtype.不需要任何复杂的合并,您可以直接复制列,填充 NaN,并设置 dtype。 You can either do this directly, or with
pd.concat()
:您可以直接执行此操作,也可以使用
pd.concat()
:
pd.concat([df1, df2], axis=1).fillna(0).astype(int)
x y
0 1 0
1 1 1
2 1 0
3 1 1
4 1 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.