【问题标题】:How to re order the order of a data frame to match the order of 2nd data frame?如何重新排序数据帧的顺序以匹配第二个数据帧的顺序?
【发布时间】:2019-01-24 22:09:50
【问题描述】:

例如,如果我有两个数据框:

df1:

  x    y
0 1.1. 2.1
1 3.1  5.1

df2:

x    y
0 0.0  2.2
1 1.1  2.1
2 3.0. 6.6
3 3.1  5.1
4 0.2  8.8

并且我希望 df2 匹配匹配共同值的顺序,但保留顺序后不匹配的值,我将如何使用 pandas 来做到这一点?或者别的什么。

想要的输出:

new_df:

    x    y
0  1.1  2.1
1  3.1. 5.1
2  0.0  2.2
3  3.0  6.6
4  0.2  8.8

第 2-4 行我不关心顺序,只要匹配的行遵循与 df1 相同的顺序即可。我希望 df1 和 df2 的索引值相等

有什么办法吗?

抱歉,如果我提交的方式有误。

谢谢大家

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    仅使用 mergeindicator 作为默认排序

    df1.merge(df2,indicator=True,how='right')
    Out[354]: 
         x    y      _merge
    0  1.1  2.1        both
    1  3.1  5.1        both
    2  0.0  2.2  right_only
    3  3.0  6.6  right_only
    4  0.2  8.8  right_only
    

    【讨论】:

    • 唯一的问题是它在末尾添加了一个额外的行,原因不知道为什么。有什么建议吗?
    • @BVOM 你需要检查你身边的df2和df1是否有重复行
    【解决方案2】:

    pd.concatdrop_duplicates 一起使用:

     pd.concat([df1,df2]).drop_duplicates().reset_index(drop=True)
    

    输出:

         x    y
    0  1.1  2.1
    1  3.1  5.1
    2  0.0  2.2
    3  3.0  6.6
    4  0.2  8.8
    

    【讨论】:

      【解决方案3】:

      查看 .combine_first 和 .update 方法。

      df1.combine_first(df2)
      

      它们在documentation here 中有解释。

      【讨论】:

      • 这会按索引重新创建行...他需要值匹配,检查您的输出,您有 3.1、5.1 的重复行
      猜你喜欢
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2020-04-25
      • 1970-01-01
      • 2021-10-27
      • 2018-04-28
      相关资源
      最近更新 更多