python错误:''TypeError:只有length-1数组可以转换为Python标量''

时间:2014-02-08 14:11:40

标签: python numpy

我正在编写monty hall问题的模拟,我无法理解导致此错误的原因。如果您不熟悉monty hall问题,那么这是一个假想的游戏节目,其中有3个门,一个门后面有奖品,两个门没有任何东西。参赛者选择一扇门,然后主人打开一个未获胜的门,让选手可以选择切换或留下他们的原始选秀权。原始选择有1/3的机会是正确的,并且转换策略有2/3的机会是正确的。

我的第一个功能需要2个阵列,这些阵列是随机选择的门,然后创建第三个阵列,即门

import numpy as np
import pandas as pd


def reveal_and_switch(win_door,first_pick):
    '''Create arrays for the door to be revealed by the host and the switch door'''
    #Take in arrays for the winning door and the contestant's first pick
    doors = [1,2,3]
    switch_door = np.array([0]*len(win_door))
    for i in range(len(switch_door)):
        if first_pick[i] != win_door[i]:
            switch_door[i] = win_door[i]
        else:
            del doors[np.searchsorted(doors,first_pick[i])]
            switch_door[i] = np.random.choice(doors)

    #print switch_door
    return switch_door


def create_doors(iterations):
    '''Create a DataFrame with columns representing the winning doors,
    the picked doors and the doors picked if the player switches and the
    accumulating probabilities'''
    win_door = np.random.random_integers(1,3,iterations)
    first_pick = np.random.random_integers(1,3,iterations)
    switch_door = reveal_and_switch(win_door,first_pick)
    #allocate memory for 
    denom = np.array([0]*len(win_door))
    first_win = np.array([0]*len(win_door))
    switch_win = np.array([0]*len(win_door))
    switch_prob = np.array([0]*len(win_door))
    stay_prob = np.array([0]*len(win_door))

    for i in len(range(switch_door)):
        denom[i] = i + 1
        if switch_door[i] == win_door[i]:
            switch_win[i] = 1
            first_win[i] = 0
        elif first_pick[i] == win_door[i]:
            switch_win[i] = 0
            first_win[i] = 1



    switch_prob = np.cumsum(switch_win)/denom
    stay_prob = np.cumsum(first_win)/denom
    df = pd.DataFrame({'iterations': iterations,
                     'Stubborn Win': first_win,
                     'Switch Win': switch_win,
                     'stubborn probability': stay_prob,
                     'switch probability': switch_prob})
    print df
    return df

当我调用create_doors(10)时,我得到了这个:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 14, in create_doors
TypeError: only length-1 arrays can be converted to Python scalars

1 个答案:

答案 0 :(得分:1)

重现这样的错误:

In [32]: a
Out[32]: array([0, 1, 2])

In [33]: range(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-5515275ab580> in <module>()
----> 1 range(a)

TypeError: only length-1 arrays can be converted to Python scalars

在您的代码range(switch_door)中,它就像我的range(a)

BTW,在你的代码中,

denom = np.array([0]*len(win_door))
first_win = np.array([0]*len(win_door))

可以简化:

denom=np.zeros_like(win_door)
first_win = denom.copy()