python - 添加列参数时,Pandas 数据透视表按字母顺序(错误地)对分类数据进行排序

标签 python pandas

我在使用 Pandas 枢轴函数时遇到了问题。我正在尝试按月和年调整销售数据。数据集如下:

Customer - Sales - Month Name   - Year
a        - 100   - january      - 2013
a        - 120   - january      - 2014
b        - 220   - january      - 2013

为了正确排序月份名称,我添加了一列,其中月份名称作为分类数据。

dataset['Month'] = dataset['Month Name'].astype('category')
dataset['Month'].cat.set_categories(['January', 'February', 'March', 'April', 'May', 'June',      'July', 'August', 'September', 'October', 'November', 'December'],inplace=True)
dataset.pop('Month Name')

当我使用函数时:

pt = dataset.pivot_table(values="Sales", index="Month")

我得到了预期的结果

Month
January      3620302.79
February     3775507.25
March        4543839.69

但是,当我跨年份和月份旋转时,月份会按字母顺序排序。

print dataset.pivot_table(values='Sales', index="Month", columns="Year", aggfunc="sum")
Year            2011        2012        2013        2014
Month                                                   
April      833692.19   954483.28  1210847.85  1210926.61
August     722604.75   735078.52   879905.23  1207211.00
December   779873.51  1053441.71  1243745.73         NaN

如能帮助我正确排序最后一个代码示例中的月份名称,我将不胜感激。

谢谢,

弗兰克

最佳答案

您就在 pivot_table 之后,它将重新索引“月份”,从而按字母顺序排序。幸运的是,您始终可以将 dataset['Month'] 转换为 pandas.datetime 并在 pivot_table 重新索引后将其转换回字符串。

不是最好的解决方案,但这应该可以解决问题(我使用了一些随机的假人):

import pandas as pd
...
# convert dataset['Month'] to pandas.datetime by the time of pivot
# it will reindex by datetime hence the sort order is kept
pivoted = dataset.pivot_table(index=pd.to_datetime(dataset['Month']), columns='Year', \
                              values='Sales', aggfunc='sum')
pivoted
Year        2012  2013  2014
Month                       
2014-01-04   151   295   NaN
2014-02-04   279   128   NaN
2014-03-04   218   244   NaN
2014-04-04   274   152   NaN
2014-05-04   276   NaN   138
2014-06-04   223   NaN   209
...

# then re-set the index back to Month string, "%B" means month string "January" etc.
pivoted.index = [pd.datetime.strftime(m, format='%B') for m in pivoted.index]

pivoted
Year       2012  2013  2014
January     151   295   NaN
February    279   128   NaN
March       218   244   NaN
April       274   152   NaN
May         276   NaN   138
June        223   NaN   209
...

但是你会错过 'Month' 索引标签,如果你需要,你可以将数据集 ['Month'] 复制到另一列(称为 M)并转换为 datetime ,然后在 pivot_table 上设置多个索引,例如:

dataset.pivot_table(index=['M', 'Month'], ...)

关于python - 添加列参数时,Pandas 数据透视表按字母顺序(错误地)对分类数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741204/

相关文章:

python - 具有不同偏移向量的 Pandas 向量化日期偏移操作

python - 将两列坐标合并为一列

python - View 中的 Numpy reshape

python - 如何在 python 中用曲率拼接/弯曲/弯曲图像?

python - VideoWriter 输出损坏的视频文件

python - 如何在显示 Pandas Dataframe 中的列时对其进行屏蔽?

python - 如何在 pandas python 中创建 DataFrame

python - 基于正则表达式识别列并填充不同默认值的优雅方法

python - 带有三重引号的 Jupyter Notebook Python 自动文档字符串生成

python - 使用 Tk Spinbox 小部件后,Matplotlib FigureCanvasTkAgg 未检测到按键