【问题标题】:"shape mismatch" error using numpy in python在 python 中使用 numpy 出现“形状不匹配”错误
【发布时间】:2013-04-01 03:47:02
【问题描述】:

我正在尝试生成一个由 0 和 1 组成的随机数组,但出现错误:形状不匹配:无法将对象广播到单个形状。错误似乎发生在randints = np.random.binomial(1,p,(n,n)) 行中。这是函数:

import numpy as np

def rand(n,p):
    '''Generates a random array subject to parameters p and N.'''

    # Create an array using a random binomial with one trial and specified
    # parameters.
    randints = np.random.binomial(1,p,(n,n))

    # Use nested while loops to go through each element of the array
    # and assign True to 1 and False to 0.
    i = 0
    j = 0
    rand = np.empty(shape = (n,n),dtype = bool)
    while i < n:
        while j < n:
            if randints[i][j] == 0:
                rand[i][j] = False
            if randints[i][j] == 1:
                rand[i][j] = True
            j = j+1
        i = i +1
        j = 0

    # Return the new array.
    return rand

print rand

当我自己运行它时,它返回&lt;function rand at 0x1d00170&gt;。这是什么意思?我应该如何将它转换为可以在其他函数中使用的数组?

【问题讨论】:

  • 你运行的是什么版本的 python 和 numpy?您上面发布的代码在i = i +1...中只有一个错误的缩进...
  • 当你运行这个程序时它打印&lt;function rand at 0x1d00170&gt;的原因是因为你的行print rand正在打印出函数对象。您需要改为调用该函数。试试:print rand(4,2)

标签: python numpy


【解决方案1】:

显然,@danodonovan 的答案是最 Pythonic 的,但如果你真的想要更类似于循环代码的东西。这是一个更简单地修复名称冲突和循环的示例。

import numpy as np

def my_rand(n,p):
    '''Generates a random array subject to parameters p and N.'''

    # Create an array using a random binomial with one trial and specified
    # parameters.

    randInts = np.random.binomial(1,p,(n,n))

    # Use nested while loops to go through each element of the array
    # and assign True to 1 and False to 0.

    randBool = np.empty(shape = (n,n),dtype = bool)
    for i in range(n):
        for j in range(n):
             if randInts[i][j] == 0:
                randBool[i][j] = False
             else:
                randBool[i][j] = True

    return randBool


newRand = my_rand(5,0.3)
print(newRand)

【讨论】:

  • 小元注释:说“上面的答案”可能并不总是正确的,因为添加了其他答案。最好参考海报的答案,即“@danodonovan 的答案”。此外,看起来您的 return 语句应该缩进到函数中。
【解决方案2】:

你不需要经历所有这些,

 randints = np.random.binomial(1,p,(n,n))

产生01 值的数组,

 rand_true_false = randints == 1

将生成另一个数组,只是将1s 替换为True,将0s 替换为False

【讨论】:

  • 另一种转换为真/假的方法是randints.astype(bool)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2019-10-20
  • 1970-01-01
  • 2016-12-19
  • 2015-11-06
  • 1970-01-01
相关资源
最近更新 更多