【问题标题】:Create index and merge two dataframes side by side after transpose转置后创建索引并并排合并两个数据帧
【发布时间】:2021-07-10 21:42:51
【问题描述】:

我有两张桌子

   NumberofTracks   NumberofAlbums  
0       200                12   

     Genres       Metal  Rock
      count       12     17 

第二张表是通过聚合转置组的结果

我需要加入两个表才能有类似的东西

                  Metal  Rock   NumberofTracks  NumberofAlbums
      count       12     17     200                12

这是我执行聚合转置的表以及我使用的代码

Genres     Songs 
Metal      Nothing Else Matters
Metal      Paranoid
Metal      Paranoid
Rock       I Can't Drive 55
Rock       Carry On Wayward Son
Metal      Walk
group=df.groupby('Genres').agg(count=('Songs','count'))
transpose=group.T

【问题讨论】:

    标签: python pandas join merge pandas-groupby


    【解决方案1】:

    假设df1是第一个表的名称,transpose是转置表的名称,可以使用:

    transpose.join(df1.set_index(transpose.index))
    
    
    
    # Result: 
    
           Metal  Rock  NumberofTracks  NumberofAlbums
    count      4     2             200              12
    

    在这里,我们利用.set_index()df1 的索引设置为数据帧transpose 的相同索引。因此,由于具有相同的索引,因此使它们能够一起.join()

    【讨论】:

      【解决方案2】:

      您可以水平连接数据框:

      pd.concat([df1, df2], axis=1)

      但由于您的索引不同,您可以创建默认索引

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

      或将索引从一个数据帧分配给另一个

      df1.index = df2.index

      pd.concat([df1, df2], axis=1)

      【讨论】:

        猜你喜欢
        • 2019-08-11
        • 1970-01-01
        • 2021-08-16
        • 2012-11-25
        • 1970-01-01
        • 1970-01-01
        • 2012-07-23
        • 1970-01-01
        • 2014-04-14
        相关资源
        最近更新 更多