【问题标题】:How can remove a column name/label from a pivot table and remaining column names drop to index name level?如何从数据透视表中删除列名/标签并将剩余的列名降至索引名称级别?
【发布时间】:2019-08-27 00:27:15
【问题描述】:

我有一个使用 CategoricalDtype 的数据透视表,因此我可以按顺序获取月份名称。如何删除列名称/标签“月份”,然后将月份缩写名称移动到与“年份”相同的级别?

... .pivot_table(index='Year',columns='Month',values='UpClose',aggfunc=np.sum))

当前输出:

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

期望的输出:

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

如果我使用data.columns.name = None,它将删除“月份”标签,但不会将月份缩写降至与“年份”相同的级别。

【问题讨论】:

  • 在末尾添加reset_index()
  • data.rename_axis(None, axis=1)
  • 您无法重置索引,因为它是 CategoricalIndex,尝试此操作时出错。

标签: python pandas pivot-table


【解决方案1】:

您需要通过执行类似Renaming columns in dataframe w.r.t 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2017-11-21
    • 1970-01-01
    相关资源
    最近更新 更多