2013-04-09 2 views
2

0s와 1s의 임의의 배열을 생성하려고하는데 오류가 발생합니다. 모양이 일치하지 않습니다. 개체를 단일 모양으로 브로드 캐스팅 할 수 없습니다. 이 오류는 줄 randints = np.random.binomial(1,p,(n,n))에서 발생하는 것으로 보입니다. 내가 스스로 그것을 실행하면파이썬에서 numpy를 사용하여 "shape mismatch"오류가 발생했습니다.

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>를 반환 여기에 기능입니다. 이것은 무엇을 의미 하는가? 어떻게 다른 함수에서 사용할 수있는 배열로 변환해야합니까?

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

01 값의 배열을 생산하고 당신은 그 모든 통해 갈 필요가 없습니다

+0

실행중인 python 및 numpy의 버전은 무엇입니까? 위에 게시 된 코드는'i = i + 1'에 오판이 있습니다 ... – Jaime

+3

이 프로그램을 실행할 때''을 인쇄하는 이유는'print rand' 행이 인쇄되기 때문입니다 함수 객체 함수를 대신 호출해야합니다. 대신'print rand (4,2)'를 시도하십시오. – Wilduck

답변

4

,

rand_true_false = randints == 1 

1True로 대체 단지로, 다른 배열을 생산합니다 및 0s와 False.

+3

True/False로 변환하는 또 다른 방법은'randints.astype (bool)'입니다. – askewchan

1

분명히 @danodonovan의 대답은 가장 Python 적이지만, 당신이 정말로 당신의 루핑 코드와 비슷한 것을 원한다면. 다음은 이름 충돌과 루프를보다 간단하게 수정 한 예입니다.

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) 
+1

작은 메타 노트 : 다른 답변이 추가 될 때 "위에있는 대답"을 말하는 것이 항상 올바르지 않을 수도 있습니다. 포스터 ("@danodonovan의 답변")로 답변을 참조하는 것이 좋습니다. 또한 return 문이 함수에 들여 쓰기되어야합니다. – Hooked

관련 문제