我如何才能将此 table 转换为这种格式?

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

我有一个 table 如下所示:

我如何在 pandas 中调整它,以便我实现:

我也想为 y3 添加这个,但是由于上面没有添加 space。

使用不带值参数的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])

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