我在Pandas索引中看到了一些有趣的行为。举例来说,假设我创建了一个Panel
p = pd.Panel(np.random.rand(3,6,9))
并以各种方式对其进行索引。
p.iloc[1,1,1].shape == ()
p.iloc[1,1,:].shape == (9,)
p.iloc[1,:,1].shape == (6,)
p.iloc[1,:,:].shape == (6,9)
p.iloc[:,1,1].shape == (3,)
p.iloc[:,1,:].shape == (9,3) # confusing
p.iloc[:,:,1].shape == (6,3) # confusing
p.iloc[:,:,:].shape == (3,6,9)
在标记为"令人困惑的"的行中,似乎Pandas在进行索引后转换DataFrame
以反转维度的顺序。为什么这样做?有没有办法阻止它?
如果我从Panel4D
:
p = pd.Panel4D(np.random.rand(3,6,9,12))
p.iloc[1,1,1,1].shape == ()
p.iloc[1,1,1,:].shape == (12,)
p.iloc[1,1,:,1].shape == (9,)
p.iloc[1,1,:,:].shape == (9,12) # ok
p.iloc[1,:,1,1].shape == (6,)
p.iloc[1,:,1,:].shape == (12,6) # confusing
p.iloc[1,:,:,1].shape == (9,6) # confusing
p.iloc[1,:,:,:].shape == (6,9,12)
p.iloc[:,1,1,1].shape == (3,)
p.iloc[:,1,1,:].shape == (12,3) # confusing
p.iloc[:,1,:,1].shape == (9,3) # confusing
p.iloc[:,1,:,:].shape == (3,9,12)
p.iloc[:,:,1,1].shape == (6,3) # confusing
p.iloc[:,:,1,:].shape == (3,6,12)
p.iloc[:,:,:,1].shape == (3,6,9)
p.iloc[:,:,:,:].shape == (3,6,9,12)
似乎每当有两个切片索引时就会发生奇怪的行为,其中一个切片索引位于前两个位置。
当然使用NumPy中的普通ndarray
时不会发生这种情况。