在 pandas 数据框中访问内部多索引级别的最后一个元素 [英] Access last elements of inner multiindex level in pandas dataframe

查看:64
本文介绍了在 pandas 数据框中访问内部多索引级别的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 multi index 熊猫数据框中,我想访问第二个索引的 last 元素,以获取第一个索引的所有值.第二个索引中的级别数取决于第一个索引的值.我浏览了 pandas多索引文档,但找不到任何能做的事情那个.

In a multi index pandas dataframe I want to access the last element of the second index for all values of the first index. The number of levels in the second index vary depending on the value of the first index. I went through the pandas multi index documentation but could not find anything that does that.

例如,对于以下数据框:

For example, for the data frame below:

arrays = [ ['bar', 'bar', 'baz', 'foo', 'foo', 'foo',   'qux'],
           ['one', 'two', 'one', 'one', 'two', 'three', 'one']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(7, 3), index=index, columns=['A', 'B', 'C'])
df
                 A         B         C
first second
bar   one     0.289163 -0.464633 -0.060487
      two     0.224442  0.177609  2.156436
baz   one    -0.262329 -0.248384  0.925580
foo   one     0.051350  0.452014  0.206809
      two     2.757255 -0.739196  0.183735
      three  -0.064909 -0.963130  1.364771
qux   one    -1.330857  1.881588 -0.262170

我想得到:

                 A         B         C
first second
bar   two     0.224442  0.177609  2.156436
baz   one    -0.262329 -0.248384  0.925580
foo   three  -0.064909 -0.963130  1.364771
qux   one    -1.330857  1.881588 -0.262170

我正在使用的 dataframes 有超过 10M 行,因此我想避免显式循环.

The dataframes I am working with have over 10M lines so I want to avoid explicit looping.

推荐答案

使用 groupby 因为 last 失去了第二级:

print (df.groupby(level='first').last())         
              A         B         C
first                              
bar    0.053054 -0.555819  0.589998
baz   -0.868676  1.293633  1.339474
foo    0.407454  0.738872  1.811894
qux   -0.346014 -1.491270  0.446772

这篇关于在 pandas 数据框中访问内部多索引级别的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆