python - 按月份名称对 Pandas 数据框系列进行排序

标签 python pandas sorting date dataframe

我有一个 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

最佳答案

您可以使用分类数据通过 pd.Categorical 进行正确排序:

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", 
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
df['months'] = pd.Categorical(df['months'], categories=months, ordered=True)
df.sort_values(...)  # same as you have now; can use inplace=True

当您指定类别时,pandas 会记住指定的顺序作为默认排序顺序。

文档:Pandas 类别 > sorting & order .

关于python - 按月份名称对 Pandas 数据框系列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042915/

相关文章:

python - 根据条件填充行

python - 如何将阈值应用于 pandas DataFrame 列并输出超出阈值的行?

python-3.x - 计算数值列 Pandas 中的字符串值

c# - 按最低数字出现的次数对列表进行排序

excel - 在 Excel 中对排名数据进行排序,同时将重复项列为不同的整数

c - 在 C 中实现最小堆

python - 为什么 tensorflow reshape 数组超出范围

python - 使用 VapourSynth ffms2 插件获取视频帧的时间戳

python - linux/wine/python-os 参数忽略错误

pandas - 从时间索引数据框中删除一行