Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫,如何访问多索引数据帧?_Python_Python 2.7_Pandas - Fatal编程技术网

Python 熊猫,如何访问多索引数据帧?

Python 熊猫,如何访问多索引数据帧?,python,python-2.7,pandas,Python,Python 2.7,Pandas,显示我的代码 >>> 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)}) >>

显示我的代码

>>> 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'])

正如您所看到的,多索引数据帧与普通数据帧不同,因此如何访问多索引数据帧中的数据。

访问多索引数据帧中的数据与访问普通数据帧中的数据类似。例如,如果您想读取(a,data1.two)处的数据,只需执行以下操作:
new_-df['data1']['two']['a']
new_-df.loc['a',('data1','two')]


请阅读以了解更多详细信息。

尽管遵循文档并不容易(一节中的解释),但请记住多级索引是基于元组索引的,因此访问数据需要
loc
和元组,即使存在不使用
loc
甚至不使用元组的不明确快捷方式。