【问题标题】:Merging Dataframes on Month, Or Unlike Column & Grouping [duplicate]按月合并数据框,或与列和分组不同[重复]
【发布时间】:2020-01-18 23:11:21
【问题描述】:

我想根据月份列/字段合并或加入三个数据框,然后按标题分组。

df1:

Month Year    TotalNumberofStreams  TitleSortName
9     2018    1529                  Movie A
9     2018    368                   Movie B
1     2018    703                   Movie C
1     2018    2278                  Movie D
1     2018    382                   Movie E

df2:

Month   Year    video_view  TitleSortName   
9       2018    3           Movie A        
9       2018    6           Movie B        
3       2017    9           Movie C       
3       2017    4           Movie D        
3       2017    3           Movie E        

df3:

    Month   Year    Views   TitleSortName
    9       2018    243     Movie A
    9       2018    156     Movie B
    9       2018    133     Movie C

期望的输出:

Month Year  Views  video_view  views TotalNumberofStreams TitleSortName
9     2018  NaN    NaN         NaN   1529                 Movie A
9     2018  NaN    3           NaN   NaN                  Movie A
9     2018  243    NaN         NaN   NaN                  Movie A

尝试:

我尝试基于 TitleSortName 进行合并,这里的代码如下:

merge=df1.merge(df2, how='outer',left_on='TitleSortName',right_on='TitleSortName')

但是,这会返回重复项,以及大量数据,这让我需要进行更多的清理工作。

我也尝试按月份加入:

join_df = df1.join(df2.set_index('Month'),on='Month')

这会返回Value Error: Pandas join issue: columns overlap but no suffix specified

我在网上浏览了不同的文章,我发现也许我可以使用 for 循环遍历月份列并将行保存到相似的列表中并返回我想要的行,以及 lambda join函数,例如:

lambda x: "/" .join(x), based on the desired columns

有没有更简单的方法可以做到这一点,或者有什么方法可以达到我想要的结果?

【问题讨论】:

  • 您需要from functools import reduce df = reduce(lambda left,right: pd.merge(left,right,on=['Month','Year','TitleSortName']), [df1, df2, df3]) 吗?如果是,则为dupe
  • 你想要的输出没有意义。为什么NaN这么多,为什么只有电影A 3次?

标签: pandas join indexing merge group-by


【解决方案1】:

你的分组没有意义。但是对于合并,您可以这样做。

 df1 = pd.DataFrame(np.array([
    [9, 2018, 1529,'A'],
    [9,2018, 368, 'B'],
    [1,2018, 703, 'C'],
    [1,2018,2278,'D']]),
    columns=['Month', 'Year', 'TotalNumberOfStreams','Title'])
df2 = pd.DataFrame(np.array([
    [9,2018, 3, 'A'],
    [9,2018, 6, 'B'],
    [3,2017,5, 'C']]),
    columns=['Month', 'Year', 'Video Views','Title'])
df3 = pd.DataFrame(np.array([
    [9,2018,243,'A'],
    [9,2018,156,'B']]),
    columns=['Month', 'Year', 'Total Views','Title'])


merged_df=df1.merge(df2,on=['Month','Year','Title']).merge(df3,on=['Month','Year','Title'])

merged_df
Out[32]: 
  Month  Year TotalNumberOfStreams Title Video Views Total Views
0     9  2018                 1529     A           3         243
1     9  2018                  368     B           6         156

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2020-08-31
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2011-12-15
    相关资源
    最近更新 更多