【问题标题】:Sort dataframe by new index after grouping in pandas在熊猫中分组后按新索引对数据框进行排序
【发布时间】:2017-10-12 19:56:22
【问题描述】:

我需要按记录为字符串的日期对数据框进行排序,因此当我绘制值时,日期会按顺序绘制。我按日期将其分组grouped = datanew.groupby(['Date']).sum() 所以sort_values('Date') 不起作用。我试过这个

grouped = datanew.sort_values(by='Date',ascending=False).groupby('Date').sum()

我也试过这个:

date = sort.reset_index()
sortd = date.sort_values(by='Date', ascending=False)

但在这种情况下,它按索引而不是按“日期”对我的 df 进行排序,这让我感到困惑。

感谢您的帮助。

【问题讨论】:

    标签: python-2.7 pandas


    【解决方案1】:

    我认为你可以使用to_datetime + sort_index + strftime + plot

    df.index = pd.to_datetime(df.index, format='%d_%b')
    df = df.sort_index()
    df.index = df.index.strftime('%d_%b')
    df.plot()
    

    示例:

    np.random.seed(10)
    df = pd.DataFrame({'a':[3,5,6,1]}, index=['11_May','12_May','1_May', '2_May'])
    print (df)
            a
    11_May  3
    12_May  5
    1_May   6
    2_May   1
    
    df.index = pd.to_datetime(df.index, format='%d_%b')
    df = df.sort_index()
    df.index = df.index.strftime('%d_%b')
    print (df)
            a
    01_May  6
    02_May  1
    11_May  3
    12_May  5
    
    df.plot()
    

    【讨论】:

    • 完成! :) 谢谢。
    • 嗨!我希望你能在我的情节上进一步帮助我。现在我在添加注释时遇到问题。我收到此错误:ValueError: invalid literal for float(): 10_May 尝试访问索引时:plt.annotate('Peak', (grouped.index[9], grouped['L'][9]), xytext=(15, 15), textcoords='offset points', arrowprops=dict(arrowstyle='-|>')) 我认为设置索引to_datetime 然后strftime 解决了这个问题,但熊猫仍然希望它是一个浮动...
    • 什么返回 grouped.index[9] 和什么 grouped.index['L'][9] ?第二个似乎有点奇怪。
    • grouped.index[9] 返回 u'10_May' 而grouped['L'][9] 返回 10.0。我只是想在图表上定位点以添加注释。
    • 嗯,你觉得像this 吗?我认为最好的方法是创建新问题 - 不确定我是否知道可以提供帮助,因为我对 matplotlib 的了解只是基本的。祝你好运!
    猜你喜欢
    • 2019-04-12
    • 2018-02-07
    • 1970-01-01
    • 2017-01-12
    • 2013-10-09
    • 2013-12-15
    • 2021-08-08
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多