Skip to main content
 首页 » 编程设计

python之索引 pandas.Panel 违反直觉还是错误

2025年05月04日7qlqwjy

我在理解 pandas.Panel(3D 数据结构)的索引时遇到了一些问题。在documentation据说索引的工作原理是:

Getting values from an object with multi-axes selection uses the following notation (using .loc as an example, but applies to .iloc and .ix as well). Any of the axes accessors may be the null slice :. Axes left out of the specification are assumed to be :. (e.g. p.loc['a'] is equiv to p.loc['a', :, :])

p.loc[item_indexer,major_indexer,minor_indexer]

现在我假设当提取 DataFrame 时,剩余索引的顺序不会改变,但是:

from pandas import Panel 
from numpy import arange 
p = Panel(arange(24).reshape(2,3,4)) 
p.shape 
Out[4]: (2, 3, 4) 
p.iloc[0].shape # original order 
Out[5]: (3, 4) 
p.iloc[:,0].shape # transposed 
Out[6]: (4, 2) 
p.iloc[:,:,0].shape # transposed 
Out[7]: (3, 2) 
p.iloc[:,0,:].shape # transpose (same as [6]) 
Out[8]: (4, 2) 
p.iloc[1:,0,:].shape # Slicing item_indexer, then transpose 
Out[9]: (4, 1) 
p.iloc[1:,0].shape # Expected to get the same as [9], but slicing minor_indexer instead???? 
Out[10]: (3, 2) 

知道为什么在索引 major_index 或 minor_index 而不是 item_index 时转置 DataFrame 吗?为什么最后一个示例与之前的不同?

Link to github issue

请您参考如下方法:

最近在github issue中有一些讨论. Pandas 似乎不太适合 N 维数据(N >= 3)。有一个替代模块 xray ,这类似于 pandas,但用于 ND 数据。否则,您可以使用带有 MultiIndex 的普通 pandas (2D) DataFrames 来模拟 ND 数据。