python - 对于选定数字的循环迭代(不使用范围)
问题描述
这是一个示例代码,但基本上我试图只选择一定范围的数字,比如 2、4 和 6,并将 3D 随机值数组的第一个轴乘以前 2,然后乘以 4 和 6,然后存储新数组(其大小仍应为 3、30 和 10)。我一直收到这个错误。我正在做的事情很简单,但我对我的 for 循环有什么问题感到困惑?我最初尝试过 np.array([2,4,6]) 但我仍然遇到同样的错误。
data = np.random.rand(3,30,10)
data_new = np.zeros((data.shape))
for i in [2,4,6]:
data_new[i,:,:] = data[i]*i
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/tmp/ipykernel_202420/2883607738.py in <module>
4
5 for i in [2,4,6]:
----> 6 data_new[i,:,:] = data[i]*i
7
IndexError: index 4 is out of bounds for axis 0 with size 3
解决方案
我想你的意思是:
for i in [2,4,6]:
data_new[:, :, i] = data[:, :, i]*i
推荐阅读
- python - 我无法识别缺失的论点
- python - 什么是最合适的方法来创建整数索引列表或 json 数组元素的字典?
- r - 跨时间框架可视化分类数据
- python-3.x - 如何将密集矩阵作为 Tfidf 变压器的输入?
- react-native - 无法从一个屏幕导航到另一个屏幕
- sql - 在 SQL 中连接两个查询的结果并在给定条件下生成结果
- python - 将 Python 函数应用于 Pandas 分组的 DataFrame - 加速计算的最有效方法是什么?
- java - 如何部分自动布局图流图
- add-in - 关于 DraftSight / SolidWorks API 的新手提示
- html - 无法单击菜单项_Selenium