枢转基于唯一值
问题描述:
我有一个数据帧像这样:枢转基于唯一值
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()
到透视表或重塑的方法吗?
答
您可以通过.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]
获得:
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
:
Land_Cover0 Land_Cover1 Land_Cover2
Allotment
Annex PHP WMTGP SP
Berg BNW SP WMTGP
,你可以与原来的DataFrame
的去欺骗版本进行合并