【问题标题】:merge two DataFrame with two columns and keep the same order with original indexes in the result将两个 DataFrame 与两列合并,并与结果中的原始索引保持相同的顺序
【发布时间】:2021-04-22 11:26:31
【问题描述】:

我有两个熊猫数据框。两个数据框都有两个键列和一个值列用于合并。我想在合并结果中保持与原始索引相同的顺序。

  • 其他数据框中的键和值可能丢失或更改。
  • 数据的顺序很重要。您不能按合并结果中的键或值对它们进行排序。

应该是这样的:

df1_index/df2_index/results仅用于演示。

我尝试将mergeouter 一起使用:

df1 = pd.DataFrame({
    "key1": ['K', 'K', 'A1', 'A2', 'B1', 'B9', 'C3'],
    "key2": ['a5', 'a4', 'a7', 'a9', 'b2', 'b8', 'c1'],
    "Value1": ['apple', 'guava', 'kiwi', 'grape', 'banana', 'peach', 'berry'],
})

df2 = pd.DataFrame({
    "key1": ['K', 'A1', 'A3', 'B1', 'C2', 'C3'],
    "key2": ['a9', 'a7', 'a9', 'b2', 'c7', 'c1'],
    "Value2": ['apple', 'kiwi', 'grape', 'banana', 'guava', 'orange'],
})

merged_df = pd.merge(df1, df2, how="outer", on=['key1', 'key2'])

但它只是在行尾添加了缺失的键:

如何合并和对齐它们?

【问题讨论】:

  • 你能解释一下为什么 K-a9 应该排在 K-a4 之前吗?一个来自 DF1,另一个来自 DF2,我不明白你如何定义他们的顺序
  • @BingWang key1/key2的顺序不保证。可能是K-a5 / K-a4 / K-a9。我只关心df1_index & df2_index

标签: pandas


【解决方案1】:

在构建合并后的数据帧时,从每个数据帧中获取索引值。

merged_df = pd.merge(df1, df2, how="outer", on=['key1', 'key2'])

使用combine_first 组合index_xindex_y

merged_df['combined_index'] =merged_df.index_x.combine_first(merged_df.index_y)

使用combined_index & index_x 删除不需要的列并重置索引进行排序。

output = merged_df.sort_values(
    ['combined_index', 'index_x']
).drop(
    ['index_x', 'index_y', 'combined_index'], axis=1
).reset_index(drop=True)

这会产生以下输出:

  key1 key2  Value1  Value2
0    K   a5   apple     NaN
1    K   a9     NaN   apple
2    K   a4   guava     NaN
3   A1   a7    kiwi    kiwi
4   A3   a9     NaN   grape
5   A2   a9   grape     NaN
6   B1   b2  banana  banana
7   C2   c7     NaN   guava
8   B9   b8   peach     NaN
9   C3   c1   berry  orange

【讨论】:

  • 太棒了!有用。我需要在df1df2 中手动构建index_xindex_y 吗?合并后有什么方便的方法可以访问df1df2中的索引吗?
  • 在合并之前,您必须分别通过 df1.reset_index()df2.reset_index() 构建获取索引。
猜你喜欢
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 2017-09-02
  • 1970-01-01
相关资源
最近更新 更多