pandas ,如何访问多索引数据框? [英] pandas, how to access multiIndex dataframe?

查看:50
本文介绍了 pandas ,如何访问多索引数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显示我的代码

<预><代码>>>>df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'], \'key2': ['一', '二', '一', '二', '一'], \'data1': np.random.randn(5), \'data2': np.random.randn(5)})>>>new_df = df.groupby(['key1', 'key2']).mean().unstack()>>>打印 new_df数据1 数据2key2 一二一二钥匙 1a -0.070742 -0.598649 -0.349283 -1.272043b -0.109347 -0.097627 -0.641455 1.135560>>>打印 new_df.columnsMultiIndex(levels=[[u'data1', u'data2'], [u'one', u'two']],标签=[[0, 0, 1, 1], [0, 1, 0, 1]],名称=[无,u'key2'])

如您所见,MultiIndex 数据帧与普通数据帧不同,那么如何访问 MultiIndex 数据帧中的数据.

解决方案

在多索引数据帧中访问数据类似于在一般数据帧上的方式.例如,如果要读取 (a, data1.two) 处的数据,只需执行以下操作:new_df['data1']['two']['a']new_df.loc['a', ('data1', 'two')]

请阅读官方文档了解更多详情.

Show my code

>>> df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'], \
                   'key2': ['one', 'two', 'one', 'two', 'one'], \
                   'data1': np.random.randn(5), \
                   'data2': np.random.randn(5)})

>>> new_df = df.groupby(['key1', 'key2']).mean().unstack()
>>> print new_df
         data1               data2
key2       one       two       one       two
key1
a    -0.070742 -0.598649 -0.349283 -1.272043
b    -0.109347 -0.097627 -0.641455  1.135560 
>>> print new_df.columns
MultiIndex(levels=[[u'data1', u'data2'], [u'one', u'two']],
       labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
       names=[None, u'key2'])

As you can see, the MultiIndex dataframe is different with normal dataframes, so how to access the data in the MultiIndex dataframe.

解决方案

Accessing data in multiindex dataframe is similar to the way on a general dataframe. For example, if you want to read data at (a, data1.two), you can simply do: new_df['data1']['two']['a'] or new_df.loc['a', ('data1', 'two')]

Please read the official docs for more details.

这篇关于 pandas ,如何访问多索引数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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