gpt4 book ai didi

python - Pandas ,如何访问 multiIndex 数据框?

转载 作者:太空狗 更新时间:2023-10-30 01:00:13 25 4
gpt4 key购买 nike

显示我的代码

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

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

最佳答案

访问多索引数据帧中的数据类似于一般数据帧的方式。例如,如果你想读取 (a, data1.two) 处的数据,你可以简单地执行:new_df['data1']['two']['a'] new_df.loc['a', ('data1', 'two')]

请阅读official docs了解更多详情。

关于python - Pandas ,如何访问 multiIndex 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com