首页 > 解决方案 > 传递值的形状是 (6, 4),索引意味着 (4, 4)

问题描述

我正在尝试制作一个 Pandasandas DataFrame,数据为零,形状为 (6,4),列是

col=['Example', 'Example', 'Example', 'Example']

并且索引是列表列表:

ind=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

我正在这样做:

pd.DataFrame(np.zeros((6,4)), columns = col, index=ind )

但它返回一个错误

Shape of passed values is (6, 4), indices imply (4, 1)

我试图用一个元组替换列表并且它有效!我在徘徊为什么会发生这个错误以及如何解决它

标签: pythonpandas

解决方案


您需要将不可变对象作为索引传递,以便索引考虑 6 个索引。您可以通过将每个子列表转换为元组来做到这一点[tuple(i) for i in ind]-

ind=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
col=['Example', 'Example', 'Example', 'Example']
pd.DataFrame(np.zeros((6,4)), columns = col, index=[tuple(i) for i in ind])
              Example  Example  Example  Example
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0
(1, 2, 3, 4)      0.0      0.0      0.0      0.0

您可以从中创建一个多索引,以便索引具有 4 个级别。

ind=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
col=['Example', 'Example', 'Example', 'Example']
print(pd.DataFrame(np.zeros((6,4)), columns = col, index=pd.MultiIndex.from_tuples(ind)))
         Example  Example  Example  Example
1 2 3 4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0
      4      0.0      0.0      0.0      0.0

#Here first level is all 1 and second level is all 2 ... and so on

推荐阅读