Python 无法更改np元素的值

Python 无法更改np元素的值,python,numpy,Python,Numpy,我试图在给定索引处更改np数组的值 def mutate(child): if np.random.rand() < MUTATION_RATE: newgene = np.random.randint(low=1, high=98) randgene = np.random.randint(low=0, high=10) print(randgene) if newgene not in child:

我试图在给定索引处更改np数组的值

def mutate(child):
    if np.random.rand() < MUTATION_RATE:
        newgene = np.random.randint(low=1, high=98)
        randgene = np.random.randint(low=0, high=10)
        print(randgene)
        if newgene not in child:
            child[0][randgene] = newgene
        else:
            newgene = np.random.randint(low=1, high=98)
            child[0][randgene] = newgene
    else:
        child = child    
    child = np.sort(child)
    
    return child
def突变(子项):
如果np.random.rand()<变异率:
newgene=np.random.randint(低=1,高=98)
randgene=np.random.randint(低=0,高=10)
印刷品(兰德金)
如果newgene不在儿童中:
child[0][randgene]=newgene
其他:
newgene=np.random.randint(低=1,高=98)
child[0][randgene]=newgene
其他:
孩子
child=np.sort(child)
返回儿童

所以我会传递一个数组,比如说,数组([0,3,17,42,48,51,75,76,94,99]),带有形状(10),但执行此方法时,我会得到一个错误'numpy.int32'对象不支持项分配。

问题是您的访问语法是针对2D数组的:

        child[0][randgene] = newgene
child[0]
是数组的第一个元素
0
<代码>0[randgene]没有意义;例如,
0
的第三个元素是什么

去掉作业中的
[0]

import numpy as np
MUTATION_RATE = 0.3
def mutate(child):
    if np.random.rand() < MUTATION_RATE:
        newgene = np.random.randint(low=1, high=98)
        randgene = np.random.randint(low=0, high=10)
        print(randgene)
        if newgene not in child:
            child[randgene] = newgene
        else:
            newgene = np.random.randint(low=1, high=98)
            child[randgene] = newgene
    else:
        child = child    
    child = np.sort(child)
    
    return child

kid = np.array([ 0, 3, 17, 42, 48, 51, 75, 76, 94, 99])
print(kid)

print(mutate(kid))

如果它有形状(10,),那你为什么要用二维索引它?@TimRoberts你是对的lol,我又看了一遍,我实际上错误地将数组的形状改为(1,10),而不是(10,),这就是为什么要做二维索引
[ 0  3 17 42 48 51 75 76 94 99]
5
[ 0  3 17 21 42 48 75 76 94 99]