【问题标题】:merging two pandas dataframe with one common column将两个熊猫数据框与一个公共列合并
【发布时间】:2021-10-10 10:18:43
【问题描述】:

我有两个看起来像这样的数据框:

50       51           100            The Treasure of the Sierra Madre (1948)
51       52            98                                          Up (2009)
52       53           100             12 Angry Men (Twelve Angry Men) (1957)
53       54           100      The 400 Blows (Les Quatre cents coups) (1959)

                                    title viewers_score number_of_viewers_ratings
0  12 Angry Men (Twelve Angry Men) (1957)            97                    103672
1                     The 39 Steps (1935)            86                     23647
2     The Adventures of Robin Hood (1938)            89                     33584
3                    All About Eve (1950)            94                     44564
4   All Quiet on the Western Front (1930)            89                     17768

dataframes head from terminal

我想加入他们,我试过 pandas 'merge':

df_merge = pd.merge(df,df_,on='title)

但它不起作用,因为数据框中的标题列的顺序不同,所以当我尝试它时,我在所有行中都得到一个错误,因此一个空数据框。如何根据共同的“标题”列合并它们两者?

【问题讨论】:

  • 您在两个数据框中都没有相似的标题,因此您得到空结果。例如,绿野仙踪在第一个数据帧中,但不在第二个数据帧中。
  • 这不是完整的数据框,它有 100 行,我只显示前 5 行
  • 然后发布这些重叠的。
  • 我编辑了第一个数据框
  • 合并成功,12 Angry Men 在第三个数据框中。您的数据中有错字、多余的空格或其他内容。

标签: python pandas dataframe


【解决方案1】:

合并数据框如下所示:

df_merge = df.merge(df_, on='title')

【讨论】:

  • 我认为语法很好,问题是两个数据帧中的标题顺序不同,所以我得到了一个空数据帧.......PS。我试过你的,还是不行。
  • @MarcoNashaat 列的顺序无关紧要。将您的数据框作为文本发布在您的问题中。顺便说一句,您在这里发布的内容没有相同的标题,也许是这个原因?
  • 你能举个数据的例子吗?
  • @Michael 不,它们是完全相同的标题。我只显示前几行
  • @kağanhazalkoçdemir 两个数据框的图像在帖子中链接。
【解决方案2】:
left_table.merge(right_table, on='title')

就是这样。如果您有错误,您没有提供太多信息来查看它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2017-06-11
    • 2016-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多