python错误:“TypeError:只能将length1数组转换为python标量”

2024-10-02 16:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个蒙蒂霍尔问题的模拟,我一辈子都不明白是什么导致了这个错误。如果你不熟悉蒙蒂霍尔的问题,这是一个假设的游戏表演,有三个门,一个门后有一个奖品,两个门没有任何东西。参赛者选择一扇门,然后主持人打开一扇未得奖的门,让参赛者选择切换或保持原来的选择。原来的选择有1/3的机会是正确的,而转换策略有2/3的机会是正确的。

我的第一个函数有两个数组,它们是随机选择的门,然后创建第三个数组,即门

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

Tags: andtheinforlennprandomarray