【问题标题】:ValueError: all the input arrays must have same number of dimensions, (numpy error)ValueError:所有输入数组必须具有相同的维数,(numpy错误)
【发布时间】:2018-06-12 17:09:47
【问题描述】:
test = np.array([20, 21, 22, 23, 22, 21])
test = test.astype(float)
result = np.zeros((1,1))
for i in range(len(test)-3):
    d = np.abs(test[i+3]-test[i])
    #print(d)
    v = 0
    for j in range(3):
        v = v + np.asscalar(
                np.abs(test[i+3-j] - test[i+3-(j+1)]))
    out = d / v
    result = np.hstack((result, out))

我希望这段代码的结果是这样的 numpy 数组的形状 -> (3,1) 正常输出原本应该如下所示:[1, 0.333, 0.333] 然而,当我运行这段代码时,我得到了一个类似标题的错误。

【问题讨论】:

  • 你不能在用result=np.append(result, out) 声明result =[] 后追加到一个数组吗?不过,这将附加到位。

标签: python arrays numpy


【解决方案1】:
test = np.array([20, 21, 22, 23, 22, 21])
test = test.astype(float)

test 是 (6,) 形状数组

result = np.zeros((1,1))

result 是 (1,1)

for i in range(len(test)-3):
    d = np.abs(test[i+3]-test[i])
    #print(d)
    v = 0
    for j in range(3):
        v = v + np.asscalar(
                np.abs(test[i+3-j] - test[i+3-(j+1)]))
    out = d / v

out 是一个标量,对吧?

    result = np.hstack((result, out))

hstack 将其输入转换为数组:

In [4]: np.array(3).shape
Out[4]: ()

尝试将 (1,1) 数组与 () 数组连接会产生此错误:

In [3]: np.hstack((np.zeros((1,1)), 3))
ValueError: all the input arrays must have same number of dimensions

一般来说,如果你想在一个循环中连接多个值,最好将它们连接到一个列表中,然后再创建一个数组。列表append 更快。

result = []
for i in range...

    result.append(out)
result = np.array(result)

也就是说,我怀疑这可以在没有循环的情况下计算出来,尽管我需要时间并彻底了解您首先要做什么。逻辑不明显。

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 2017-06-18
    • 2016-12-15
    • 2018-06-23
    • 1970-01-01
    • 2022-10-25
    • 2019-04-03
    • 2018-12-18
    • 2018-05-18
    相关资源
    最近更新 更多