【问题标题】:Turn rows duplicates into columns/headers将行重复项转换为列/标题
【发布时间】:2020-12-22 05:13:01
【问题描述】:
    Category    Value
0   name    ggg
1   street  zzz
2   houseNumber 141
3   postalCode  4500
4   city    TRE
5   country GGG
6   lat 59.932996
7   lng 43.054331
8   name    BBB
9   street  TTT
10  houseNumber 175
11  postalCode  1352
12  city    FRT
13  country GFD
14  lat 20.741285
15  lng 47.336491

如何将重复的行变成表头,将Values 变成行。

这很有可能是重复的,但没有任何方法对我有用。

#output

  name street houseNumber postalCode ....
1  ggg ...
2  kkk ...
3  bbb ...
4
5
...

【问题讨论】:

    标签: python pandas pivot


    【解决方案1】:

    让我们尝试使用ffillpivot创建添加列

    df['name'] = df.Value.where(df.Category.eq('name')).ffill()
    out = df.query('Category!=name').pivot(index='name',columns='Category',values='Value')
    Out[106]: 
    Category city country houseNumber        lat        lng name postalCode street
    name                                                                          
    BBB       FRT     GFD         175  20.741285  47.336491  BBB       1352    TTT
    ggg       TRE     GGG         141  59.932996  43.054331  ggg       4500    zzz
    

    【讨论】:

      【解决方案2】:

      我认为pd.pivot 可以使用基于类别的自定义索引。

      df1 = pd.pivot(df.assign(idx=df.groupby('Category').cumcount()),
                     index='idx',
                     columns='Category')
      
      print(df1)
      

      【讨论】:

        【解决方案3】:

        如果每个块正好有 8 行长,您可以简单地使用:

        df.set_index(df.index//8).pivot(columns='Category', values='Value')
        

        结果:

        Category city country houseNumber        lat        lng name postalCode street
        0         TRE     GGG         141  59.932996  43.054331  ggg       4500    zzz
        1         FRT     GFD         175  20.741285  47.336491  BBB       1352    TTT
        

        【讨论】:

          猜你喜欢
          • 2013-06-22
          • 1970-01-01
          • 2019-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-06
          相关资源
          最近更新 更多