基于唯一值的透视

Pivoting based on unique values

我有一个这样的数据框:

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() 合并到枢轴 table 或重塑中?

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

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 的 de-duped 版本合并:

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