【问题标题】:Python pandas merge map with multiple values xlookupPython pandas合并地图与多个值xlookup
【发布时间】:2022-11-04 02:17:34
【问题描述】:

我有一个演员姓名的数据框:

df1

actor_id    actor_name
1   Brad Pitt
2   Nicole Kidman
3   Matthew Goode
4   Uma Thurman
5   Ethan Hawke

演员所在的电影的另一个数据框:

df2

actor_id    actor_movie movie_revenue_m
1   Once Upon a Time in Hollywood   150
2   The Others  50
2   Moulin Rouge    200
3   Stoker  75
4   Kill Bill   125
5   Gattaca 85

我想将两个数据框合并在一起,以向演员展示他们的电影名称和电影收入,所以我使用了合并函数:

df3 = df1.merge(df2, on = 'actor_id', how = 'left')

df3

actor_id    actor_name  actor_movie movie_revenue
1   Brad Pitt   Once Upon a Time in Hollywood   150
2   Nicole Kidman   Moulin Rouge    50
2   Nicole Kidman   The Others  200
3   Matthew Goode   Stoker  75
4   Uma Thurman Kill Bill   125
5   Ethan Hawke Gattaca 85

但这会涉及所有电影,所以妮可基德曼被复制了,我只想为每个演员放映一部电影。如何在不“复制”我的演员列表的情况下合并数据框?

我将如何合并按字母顺序排列的电影标题?

我将如何合并收入最高的电影名称?

谢谢!

【问题讨论】:

    标签: python pandas merge xlookup


    【解决方案1】:

    一种方法是继续合并,然后过滤结果集

    按字母顺序排列的电影标题

    # sort by name, movie and then pick the first while grouping by actor
    df.sort_values(['actor_name','actor_movie'] ).groupby('actor_id', as_index=False).first()
    
        actor_id    actor_name  actor_movie     movie_revenue
    0   1   Brad Pitt   Once Upon a Time in Hollywood   150
    1   2   Nicole Kidman   Moulin Rouge    50
    2   3   Matthew Goode   Stoker  75
    3   4   Uma Thurman     Kill Bill   125
    4   5   Ethan Hawke     Gattaca     85
    

    收入最高的电影名称

    # sort by name, and review (descending), groupby actor and pick first
    df.sort_values(['actor_name','movie_revenue'], ascending=[1,0] ).groupby('actor_id', as_index=False).first()
    
        actor_id    actor_name  actor_movie     movie_revenue
    0   1   Brad Pitt   Once Upon a Time in Hollywood   150
    1   2   Nicole Kidman   The Others  200
    2   3   Matthew Goode   Stoker  75
    3   4   Uma Thurman     Kill Bill   125
    4   5   Ethan Hawke     Gattaca     85
    

    【讨论】:

      猜你喜欢
      • 2015-09-12
      • 2019-04-17
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 2023-02-22
      • 2018-06-11
      • 2021-02-23
      • 2016-01-10
      相关资源
      最近更新 更多