我正在尝试制作一个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)
我试图用一个元组替换该列表,并且有效!我在徘徊为什么会发生此错误以及如何解决它
您将需要传递一个不可变的对象作为索引,以便该索引考虑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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句