2024-05-13 09:06:13 发布
网友
原始数据:
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
以下命令(来自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]
df.variable.unique()
[A, C, B]
以下命令(来自how can i unstack without sorting in pandas?)对我来说没问题:
并返回:
您可以通过^{} 实现这一点:
这将顺序设置为
df.variable.unique()
,即[A, C, B]
相关问题 更多 >
编程相关推荐