python - 传递值的形状是 (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)
我试图用一个元组替换列表并且它有效!我在徘徊为什么会发生这个错误以及如何解决它
解决方案
您需要将不可变对象作为索引传递,以便索引考虑 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
推荐阅读
- c# - 通过 GeckoDriver Selenium 和 C# 加载现有 FirefoxProfile 时,“System.IO.Compression.ZipStorer”的类型初始化程序引发异常
- javascript - 如何使用多个按钮使jquery计数器上下移动?
- javascript - 如何在动态加载内容中的链接上绑定“点击”?
- django - 如何从 django rest 中的单个类返回列表或检索对象?
- solidity - 如何获取与已发送事务对应的已发出事件
- reactjs - 单击复选框时如何添加行?因为我是新来的反应
- etl - 如何使用 talend 将 API 数据加载到 MYSQL 数据库中
- ios - FFMPEG 创建模糊视频
- ios - 错误 ITMS-90174:“缺少配置文件 - 应用程序必须在名为 embedded.mobileprovision 的文件中包含配置文件。”
- java - 如何将 Optional.ofNullable 下的空指针作为嵌套处理?