大Pandas的不一致选择

2024-06-01 04:56:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我看到熊猫有一些有趣的行为。举个例子,假设我创建一个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)

在标记为“fuzzing”的行中,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时,不会发生这种情况。你知道吗


Tags: 标记pandasnp方式情况random例子pd