python - 基于独特值(value)观的转变

标签 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  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() 合并到数据透视表或 reshape 中?

最佳答案

您可以通过 .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的重复数据删除版本合并:

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

关于python - 基于独特值(value)观的转变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34935172/

相关文章:

python - 将 int 转换为 16 位无符号短整型

python - 如何对包含混合数字和字符串的 DataFrame 中的数字求和

sql-server - SQL Server 将多行合并为一列

没有聚合的 SQL 数据透视表

python - 以文本文件和 oracle 表为源的 Hive、Pig 或 Python Mapreduce 哪个能提供最佳性能?

python - 如何初始化并附加到空的二维列表?

python - 如何 'unpack' pandas数据框列

python - 如何向散点图添加图例?

python - Pandas 使用单元格值作为字典键返回字典值

sql - 行值到列以及列名称到值 bigquery