【问题标题】:Merge rows from one dataframe that do not match specific columns in another dataframe Python Pandas合并一个数据框中与另一个数据框中的特定列不匹配的行 Python Pandas
【发布时间】:2017-04-24 06:53:27
【问题描述】:

我有两个数据框,想将一个数据框中没有一组匹配列的所有行合并到另一个数据框。下面是一个例子:

import pandas

df_1 = pandas.DataFrame({"question":["ABC", "ABC", "EFG", "EFG"],
                         "answer":["abc", "bcd", "efg", "fgh"],
                         "grade":[ "A", "B", "F", "A"],
                         "system":[2,1,1,2]})

df_2 = pandas.DataFrame({"question":["ABC", "ABC", "EFG", "EFG"],
                         "answer":["abc", "jkl", "efg", "qrs"]})

print(f"df_1:\n{df_1}")
print(f"\ndf_2:\n{df_2}")


# <---console output-->

df_1:
  question answer grade  system
0      ABC    abc     A       2
1      ABC    bcd     B       1
2      EFG    efg     F       1
3      EFG    fgh     A       2

df_2:
  question answer
0      ABC    abc
1      ABC    jkl
2      EFG    efg
3      EFG    qrs

如果df_2['question', 'answer'] 不在df_1 中,我如何将df_2 的行附加到df_1

想要的结果:

question    answer    grade    system
ABC         abc       A        2
ABC         bcd       B        1
EFG         efg       F        1
EFG         fgh       A        2
ABC         jkl       NaN      NaN
EFG         qrs       NaN      NaN

【问题讨论】:

    标签: python pandas join dataframe merge


    【解决方案1】:

    您需要outer 加入:

    df_1.merge(df_2, how = "outer")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-26
      • 2019-01-22
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 2021-04-19
      • 1970-01-01
      相关资源
      最近更新 更多