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
甚至不使用元组的不明确快捷方式。