简体   繁体   English

我怎样才能旋转这张表以得到它的这种格式?

[英]How can i pivot this table to get it in this format?

i have a table like the following:我有一张如下表:

在此处输入图片说明

how can i pivot this in pandas so that i achieve:我怎样才能在熊猫中旋转它,以便我实现: 在此处输入图片说明

i would like to also add this for y3 too but due to space not added above.我也想为 y3 添加这个,但由于上面没有添加空间。

Use DataFrame.pivot without values parameter and then flatten MultiIndex :使用DataFrame.pivot没有值的参数,然后压平MultiIndex

df1 = df.pivot(index='company', columns='year_active')
#alternative
#df1 = df1.set_index(['company','year_active']).unstack()
df1.columns = df1.columns.map(lambda x: f'{x[0]}_{x[1]}')
df.pivot(index='company', columns='year_active', values=['spend', 'counts', 'distinct_counts])

尝试使用它,这将满足您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM