[英]How can remove a column name/label from a pivot table and remaining column names drop to index name level?
I have a pivot table using CategoricalDtype so I can get the month names in order. 我有一个使用CategoricalDtype的数据透视表,因此可以按顺序获取月份名称。 How can I can drop the column name/label "Month" and then move the month abbreviation names to the same level as "Year"?
如何删除列名称/标签“月”,然后将月的缩写名称移到与“年份”相同的级别?
... .pivot_table(index='Year',columns='Month',values='UpClose',aggfunc=np.sum)) ... .pivot_table(index ='Year',columns ='Month',values ='UpClose',aggfunc = np.sum))
Current output: 电流输出:
Month Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
Year
1997 12.0 8.0 8.0 12.0 11.0 12.0 14.0 10.0 10.0 10.0 10.0 9.0 126.0
1998 10.0 12.0 14.0 12.0 9.0 11.0 10.0 8.0 11.0 10.0 10.0 12.0 129.0
Desired output: 所需的输出:
Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
1997 12.0 8.0 8.0 12.0 11.0 12.0 14.0 10.0 10.0 10.0 10.0 9.0 126.0
1998 10.0 12.0 14.0 12.0 9.0 11.0 10.0 8.0 11.0 10.0 10.0 12.0 129.0
If I use, data.columns.name = None
it will remove the "Month" label, but it doesn't drop the month abbreviations to the same level as "Year. 如果我使用
data.columns.name = None
,它将删除“月”标签,但不会将月的缩写降到与“年份”相同的级别。
You need to replace the column name by doing something like this Renaming columns in dataframe wrt another specific column 您需要执行以下操作来替换列名称: 重命名数据框中的列,并替换另一个特定的列
# replace the Month with year
df = df.rename(columns={"Month":"Year"})
# drop first column
df = df.iloc[1:].reset_index(drop=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.