在python中使用numpy的“形状不匹配”错误

时间:2013-04-09 15:49:40

标签: python numpy

我正在尝试生成一个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

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

2 个答案:

答案 0 :(得分:4)

你无需经历所有这些,

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

生成01值数组,

 rand_true_false = randints == 1

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

答案 1 :(得分: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)