首页 > 解决方案 > 为什么我不能将一个数组分配为另一个数组的列

问题描述

我有这个 numpy 数组

data = np.array([10.66252794 10.65999505 10.65745968 10.65492432 10.65239142 10.64985606
 10.64732069 10.64478533 10.64225243 10.63971707 10.6371817  10.6346488
 10.63211344 10.62957807 10.62704518 10.62450981 10.62197445 10.61944155
 10.61690619 10.61437082])

我希望 data 中的值位于数组结果的第 p 列中。

澄清一下,我想达到与 Matlab 相同的效果result(:,p)

我试过了

result[..., p] = data

但这给了我

ValueError: could not broadcast input array from shape (20) into shape ()

numpy的result[..., p]和Matlab的不一样吗result(:,p)

我还尝试了这里建议的分配给 NumPy 中的列?

result[...,p] = data[..., 0]只输入其中result的第一个值data10.66252794

标签: pythonnumpy

解决方案


您正在尝试将一列分配给一个明显为空的数组。如果 result 是具有 mxn 行和列的数组,则只能将形状 (20,) 的数据分配给 result 中的任何列,这样行数 m = 20。例如:

result = np.zeros((20,5))
result[:,0] = data #Assigning to column 0

推荐阅读