【问题标题】:Convert Column Values to Columns and other Values Become that New Column Values将列值转换为列,其他值成为新的列值
【发布时间】:2022-11-03 15:59:06
【问题描述】:

我有一个数据框,并希望将数据框转换为一列中的值成为具有另一列值的新列。

df = pd.DataFrame({'id': ['1','1','2','2','2','3','3','3','3'],
               'name': ['Andi','Andy','Ben','Ben','Benjamin','Charlie','Charlie','Charlie','Charles'],
               'event': ['Basket','Basket','Basket','Soccer','Soccer','Basket','Basket','Soccer','Basket'],
               'reg_num': ['435','436','123','341','231','223','115','432','67']
               })

我期望的结果是

                     Basket        Soccer
id Name
 1 Andi, Andy        435,436   
 2 Ben, Benjamin     123           231,341
 3 Charlie,Charles   223,115,67    432

我尝试分组

df2 = df.reset_index().groupby(['id','name','event'])['reg_num'].aggregate('first').unstack()

但 id 不合并名称或注册号

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    利用:

    s = df.groupby('id')['name'].agg(lambda x: ','.join(x.unique()))
    print (s)
    id
    1          Andi,Andy
    2       Ben,Benjamin
    3    Charlie,Charles
    Name: name, dtype: object
    
    df2 = (df.pivot_table(index='id', 
                          columns='event', 
                          values='reg_num', 
                          aggfunc=','.join, 
                          fill_value='')
              .assign(Name=s)
              .set_index('Name', append=True))
    print (df2)
    event                   Basket   Soccer
    id Name                                
    1  Andi,Andy           435,436         
    2  Ben,Benjamin            123  341,231
    3  Charlie,Charles  223,115,67      432
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多