不排序列名的数据帧透视?

2024-03-29 01:55:52 发布

您现在位置:Python中文网/ 问答频道 /正文

原始数据:

date   variable    value
2017    A             1
2017    C             1
2017    B             2
2018    A             1
2018    C             1
2018    B             2

我的数据透视结果:-

date   A        B        C
2017   1        2        1
2018   1        2        1

预期产量:-

date   A     C     B
2017   1     1     2
2018   1     1     2

Tags: 数据原始数据datevaluevariable产量
2条回答

以下命令(来自how can i unstack without sorting in pandas?)对我来说没问题:

print(df.unstack(0).reindex(pd.unique(df.index.get_level_values(1))).sort_index(axis=1,level=1).T)

并返回:

      A  C  B
2017  1  1  2
2018  1  1  2

您可以通过^{}实现这一点:

df.variable=pd.Categorical(df.variable,categories=df.variable.unique(),ordered=True)
df.pivot_table(index='date',columns='variable',values='value')

variable  A  C  B
date             
2017      1  1  2
2018      1  1  2

这将顺序设置为df.variable.unique(),即[A, C, B]

相关问题 更多 >