简体   繁体   English

如何在索引上合并两个 pandas 数据帧但填充缺失值

[英]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.我尝试了outerinner连接,但无济于事。 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.

相关问题 Pandas:如何使用索引位置和回填或前向填充来合并两个数据帧以查找缺失的行? - Pandas: How to merge two dataframes using index location and backfill or forward fill for missing rows? Pandas 连接/合并数据框用列中的最后一个填充缺失值 - Pandas concat/merge Dataframes fill missing values with last in column 左合并两个数据框并仅填充 Pandas 中的 NaN 值 - Left merge two dataframes and fill only NaN values in Pandas 按索引合并两个 pandas 数据帧并替换 Python 中的列值 - Merge two pandas dataframes by index and replace column values in Python 如何合并数据框和填充值 - How to merge dataframes and fill values 如何对齐许多数据帧的索引并在Pandas中填写相应的缺失值? - How to align indexes of many dataframes and fill in respective missing values in Pandas? 比较pandas数据帧的列并填充缺失值 - Compare columns of pandas dataframes and fill missing values 如何在日期时间索引和两列上合并 pandas 数据帧 - How to merge pandas dataframes on datetime index and two columns 如何将两个 pandas 数据帧合并为单个多索引 DataFrame? - How to merge two pandas DataFrames into single Multi-Index DataFrame? 如何通过比较值的范围来合并两个 Pandas 数据帧(或传输值) - How to merge two pandas dataframes (or transfer values) by comparing ranges of values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM