【发布时间】:2018-06-11 02:14:34
【问题描述】:
我有一个 Series 对象:
date price
dec 12
may 15
apr 13
..
问题陈述:我想让它按月显示,并计算每个月的平均价格,然后按月排序。
期望的输出:
month mean_price
Jan XXX
Feb XXX
Mar XXX
我想制作一个列表并将其传递给排序函数:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
但 sort_values 不支持系列。
我遇到的一个大问题是,即使
df = df.sort_values(by='date',ascending=True,inplace=True) 有效
到最初的df,但在我做了groupby 之后,它没有保持从排序的df 出来的顺序。
总之,我需要从初始数据框中这两列。使用月份 (dt.strftime('%B')) 对日期时间列和分组进行排序,排序搞砸了。现在我必须按月份名称对其进行排序。
我的代码:
df # has 5 columns though I need the column 'date' and 'price'
df.sort_values(by='date',inplace=True) #at this part it is sorted according to date, great
total=(df.groupby(df['date'].dt.strftime('%B'))['price'].mean()) # Though now it is not as it was but instead the months appear alphabetically
【问题讨论】:
-
您是否尝试过
df.sort_values(by='Date_col', inplace=True),正如this question 的答案所示? -
是的,我只是忘了提及。问题出现在 group by 之后。它只是按字母顺序排列。
-
好的,您是否尝试过this answer 中概述的在数据框组内排序的过程?
-
在我的示例中需要按月转换的日期时间的存在使得它难以实现
-
如何首先将列映射到一系列索引(因此对于每个月,将它的索引存储在
months数组中,而不是名称字符串中),然后对这些数字进行排序?
标签: python pandas sorting date dataframe