根据唯一值进行透视

时间:2016-01-21 22:02:05

标签: python pandas pivot

我有一个像这样的数据框:

Allotment  NDWI   DEM    TWI    Land_Cover
Annex      10     1.2    4      PHP
Annex      10     1.2    4      PHP
Annex      10     1.2    4      WMTGP
Annex      10     1.2    4      SP
Berg       5      1.7    5      BNW
Berg       5      1.7    5      BNW
Berg       5      1.7    5      SP
Berg       5      1.7    5      WMTGP

我希望对其进行透视,以便特定Allotment的行中的所有唯一值都成为他们自己的列。

我想要的输出是:

Allotment  NDWI    DEM  TWI  Land_Cover1   Land_Cover2   Land_Cover3
Annex      10      1.2  4    PHP           WMTGP         SP
Berg       5       1.7  5    BNW           SP            WMTGP

有没有办法将.unique()合并到数据透视表或重塑?

1 个答案:

答案 0 :(得分:1)

您可以通过.unique().groupby()使用.apply()

land_cover = df.groupby('Allotment')['Land_Cover'].apply(lambda x: pd.DataFrame(x.unique()).T).reset_index(level=1, drop=True)
land_cover.columns = ['Land_Cover{}'.format(c) for c in land_cover.columns]

得到:

          Land_Cover0 Land_Cover1 Land_Cover2
Allotment                                    
Annex             PHP       WMTGP          SP
Berg              BNW          SP       WMTGP

您可以与原始DataFrame的去除版本合并:

pd.concat([df.set_index('Allotment').loc[:, ['NDWI', 'DEM', 'TWI']].drop_duplicates(), land_cover], axis=1)

           NDWI  DEM  TWI Land_Cover0 Land_Cover1 Land_Cover2
Allotment                                                    
Annex        10  1.2    4         PHP       WMTGP          SP
Berg          5  1.7    5         BNW          SP       WMTGP
相关问题