在python中使用numpy的“形状不匹配”错误(“shape mismatch” error using numpy in python)
我试图生成一个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