如何根据级别内的最新日期对pandas pivot_table进行排序?

时间:2015-11-24 15:35:42

标签: python sorting date pandas pivot-table

我已按照所需的日期顺序创建了一个DataFrame,但是,当我将其放入数据透视表时,订单会发生变化。

我想根据给定级别中任何行的最新日期对数据透视表进行排序

data = [['yellow',1,'02/01/2015'],
        ['yellow',2,'04/01/2015'],
        ['green',3,'03/01/2015'],
        ['red',4,'01/01/2015']]

    df = pd.DataFrame(data, columns=['colour','number','date'])
    df.pivot_table(index=['number','date'])

结果是

                    number
colour  date    
green   03/01/2015  3
red     01/01/2015  4
yellow  02/01/2015  1
        04/01/2015  2

我希望最终结果是一个颜色列表,其中最新日期位于顶部,基本上是每行最新日期的排序(围绕它们的星号)。结果将是: -

                    number
colour  date    
yellow  02/01/2015  2
        *04/01/2015*  3
green   *03/01/2015*    4
red     *01/01/2015*    1

我可以想到三个解决方案,但我无法解决它们

a)获取pivot_table以保持原始订单 b)使用沿latest_date_in_rows行的func对pivot_table进行排序 c)创建一个包含每种颜色的最新日期的额外列

不确定哪条路是进入熊猫世界的正确途径,但目前我被困住了:(

1 个答案:

答案 0 :(得分:0)

您可以在旋转之前记住旧的multiindex,然后按旧的multiindex reindex输出数据框。

import pandas as pd

data = [['yellow',1,'02/01/2015'],
        ['yellow',2,'04/01/2015'],
        ['green',3,'03/01/2015'],
        ['red',4,'01/01/2015']]
df = pd.DataFrame(data, columns=['colour','number','date'])
#simulate datetime column date
df['date'] = pd.to_datetime(df['date'])
#set index from columns colour and date
df = df.set_index(['colour', 'date'])
print df
#                   number
#colour date              
#yellow 2015-02-01       1
#       2015-04-01       2
#green  2015-03-01       3
#red    2015-01-01       4

#set old index to variable idx
idx = df.index
print df.index

#pivot table, it doesn't work with test data
df.pivot_table(index=['number','date'])

#reindex by old multiindex
df1 = df.reindex(idx)
print df1
#                   number
#colour date              
#yellow 2015-02-01       1
#       2015-04-01       2
#green  2015-03-01       3
#red    2015-01-01       4

编辑:

我认为问题是原始数据框没有排序。 它的multiindex是:

MultiIndex(levels=[[u'green', u'red', u'yellow'], [u'2015-01-01', u'2015-02-01', u'2015-03-01', u'2015-04-01']],
           labels=[[2, 2, 0, 1], [1, 3, 2, 0]],
           names=[u'colour', u'date'])

输出数据框的multiindexcolour排序:

MultiIndex(levels=[[u'green', u'red', u'yellow'], [u'2015-01-01', u'2015-02-01', u'2015-03-01', u'2015-04-01']],
           labels=[[0, 1, 2, 2], [2, 0, 1, 3]],
           names=[u'colour', u'date'])

您可以按级别date排序,但多索引和输出是:

idx1 = df.sortlevel(level='date').index
print idx1
MultiIndex(levels=[[u'green', u'red', u'yellow'], [u'2015-01-01', u'2015-02-01', u'2015-03-01', u'2015-04-01']],
           labels=[[1, 2, 0, 2], [0, 1, 2, 3]],
           names=[u'colour', u'date'])


#reindex by idx1
df1 = df.reindex(idx)
                   number
colour date              
red    2015-01-01       4
yellow 2015-02-01       1
green  2015-03-01       3
yellow 2015-04-01       2

因此原始reindex解决方案为multiindex