简体   繁体   中英

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.

Use DataFrame.pivot without values parameter and then flatten 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])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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