pandas 熊猫,如何访问多索引数据框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36806517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas, how to access multiIndex dataframe?
提问by GoingMyWay
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 MultiIndexdataframe is different with normal dataframes, so how to access the data in the MultiIndexdataframe.
如您所见,MultiIndex数据帧与普通数据帧不同,那么如何访问MultiIndex数据帧中的数据。
回答by Zhenhao Chen
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')]
访问多索引数据帧中的数据类似于通用数据帧中的方式。例如,如果您想读取 (a, data1.two) 处的数据,您可以简单地执行:new_df['data1']['two']['a']
或new_df.loc['a', ('data1', 'two')]
Please read the official docsfor more details.
请阅读官方文档以获取更多详细信息。