如何在Multiindex数据帧中选择第一级的最后一个键中的行?

时间:2013-04-11 15:18:10

标签: python pandas

我有一个Pandas DataFrame,如下所示:

                       data
date       signal                     
2012-11-01 a           0.04
           b           0.03
2012-12-01 a          -0.01
           b           0.00
2013-01-01 a          -0.00
           b          -0.01

我试图只根据多索引的第一级获取最后一行,在这种情况下是日期。

2013-01-01 a          -0.00
           b          -0.01

第一级索引是datetime。选择最后一行最优雅的方法是什么?

4 个答案:

答案 0 :(得分:7)

一种方法是直接访问MultiIndex的级别(并使用最后一个级别):

In [11]: df.index.levels
Out[11]: [Index([bar, baz, foo, qux], dtype=object), Index([one, two], dtype=object)]

In [12]: df.index.levels[0][-1]
Out[12]: 'qux'

并使用ix选择这些行:

In [13]: df.ix[df.index.levels[0][-1]]
Out[13]:
            0         1         2         3
one  1.225973 -0.703952  0.265889  1.069345
two -1.521503  0.024696  0.109501 -1.584634

In [14]: df.ix[df.index.levels[0][-1]:]
Out[14]:
                0         1         2         3
qux one  1.225973 -0.703952  0.265889  1.069345
    two -1.521503  0.024696  0.109501 -1.584634

(使用@Jeff's example DataFrame。)

也许更优雅的方式是使用tail(如果你知道总会有两个):

In [15]: df.tail(2)
Out[15]:
                0         1         2         3
qux one  1.225973 -0.703952  0.265889  1.069345
    two -1.521503  0.024696  0.109501 -1.584634

答案 1 :(得分:2)

在0.11(本周即将发布)中,这是一种合理的方法

In [50]: arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
   .....:           np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]

In [51]: df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

In [52]: df
Out[52]: 
                0         1         2         3
bar one -1.798562  0.852583 -0.148094 -2.107990
    two -1.091486 -0.748130  0.519758  2.621751
baz one -1.257548  0.210936 -0.338363 -0.141486
    two -0.810674  0.323798 -0.030920 -0.510224
foo one -0.427309  0.933469 -1.259559 -0.771702
    two -2.060524  0.795388 -1.458060 -1.762406
qux one -0.574841  0.023691 -1.567137  0.462715
    two  0.936323  0.346049 -0.709112  0.045066

In [53]: df.loc['qux'].iloc[[-1]]
Out[53]: 
            0         1         2         3
two  0.936323  0.346049 -0.709112  0.045066

这将在0.10.1

中起作用
In [63]: df.ix['qux'].ix[-1]
Out[63]: 
0    0.936323
1    0.346049
2   -0.709112
3    0.045066
Name: two, dtype: float64

另一种方式(这适用于0.10.1)以及

In [59]: df.xs(('qux','two'))
Out[59]: 
0    0.936323
1    0.346049
2   -0.709112
3    0.045066
Name: (qux, two), dtype: float64

答案 2 :(得分:0)

如果您的数据框df已定义了MultiIndex,则:

df2 = df.ix[df.index[len(df.index)-1][0]]

也可以。

答案 3 :(得分:0)

您可以使用iloc获取最后一行:

   df.iloc[-1]