【问题标题】:Pandas: Pivoting With Duplicate ValuesPandas:使用重复值进行透视
【发布时间】:2017-05-04 00:19:41
【问题描述】:

我想旋转一列中具有重复值的数据框,以在新列中公开相关值,如下例所示。从 Pandas 文档中,我无法弄清楚如何从这个...

name   car    model
rob    mazda  626
rob    bmw    328
james  audi   a4
james  VW     golf
tom    audi   a6
tom    ford   focus

到这里……

name   car_1  model_1  car_2  model_2
rob    mazda  626      bmw    328
james  audi   a4       VW     golf
tom    audi   a6       ford   focus

【问题讨论】:

    标签: python pandas dataframe pivot


    【解决方案1】:
    x = df.groupby('name')['car','model'] \
          .apply(lambda x: pd.DataFrame(x.values.tolist(),
                 columns=['car','model'])) \
          .unstack()
    x.columns = ['{0[0]}_{0[1]}'.format(tup) for tup in x.columns]
    

    结果:

    In [152]: x
    Out[152]:
           car_0 car_1 model_0 model_1
    name
    james   audi    VW      a4    golf
    rob    mazda   bmw     626     328
    tom     audi  ford      a6   focus
    

    如何对列进行排序:

    In [157]: x.loc[:, x.columns.str[::-1].sort_values().str[::-1]]
    Out[157]:
          model_0  car_0 model_1 car_1
    name
    james      a4   audi    golf    VW
    rob       626  mazda     328   bmw
    tom        a6   audi   focus  ford
    

    【讨论】:

      【解决方案2】:

      我们可以使用groupbycumcount设置索引

      i = df.groupby('name').cumcount() + 1
      df.set_index(['name', i2]).unstack()
      
               car       model       
                 1     2     1      2
      name                           
      james   audi    VW    a4   golf
      rob    mazda   bmw   626    328
      tom     audi  ford    a6  focus
      

      或者我们可以折叠pd.MultiIndex

      i = df.groupby('name').cumcount() + 1
      d1 = df.set_index(['name', i2]).unstack().sort_index(1, 1)
      d1.columns = d1.columns.to_series().map('{0[0]}_{0[1]}'.format)
      d1
      
      
             car_1 model_1 car_2 model_2
      name                              
      james   audi      a4    VW    golf
      rob    mazda     626   bmw     328
      tom     audi      a6  ford   focus
      

      【讨论】:

        猜你喜欢
        • 2015-09-10
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2018-12-27
        • 1970-01-01
        相关资源
        最近更新 更多