【问题标题】:Why can't I assign an array as column of another array为什么我不能将一个数组分配为另一个数组的列
【发布时间】:2020-11-06 04:13:44
【问题描述】:

我有这个 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)不一样

我也尝试了这里的建议Assigning to columns in NumPy?

result[...,p] = data[..., 0] 仅将result 放入data 的第一个值,即10.66252794

【问题讨论】:

  • 如果result 是2d 那么result[:, p] = data 应该将数据设置为第p 列
  • 结果是一维的,实际上 print(result.shape) 给了我 (20,)
  • 那么它没有任何列...那你想如何更新它的第 p 列?
  • 我错了,数据是一维的,而结果是一个空数组。所有代码都在 for 循环中,p 是计数器,因此对于每次迭代,获取分配给更改的数据值的列

标签: python numpy


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2014-04-20
    相关资源
    最近更新 更多