在 Python 中使用随机函数时每次都得到零

Sim*_*hal 4 python

我正在这样做,如下所示。最初我有一个二维数组 A = [(1,2,3) , (4,5,6)]。现在通过函数 func ,我想用随机数替换数组 A 两行中的所有元素。我正在尝试,但在执行该函数后,我将每个元素都设为 0。有人可以帮忙吗。请记住,我必须通过使用此函数 func 并执行这些切片操作来解决此问题。

import numpy as np
import random
A=np.array([(1,2,3),(4,5,6)])
def func(B):
    B[0:3]= np.random.random((1,3))
    return(B)
                    
for ic in range(0,2):
    A[ic,:]= func(A[ic,:])

print(A)    
Run Code Online (Sandbox Code Playgroud)
Output
Everytime I am getting zeros. There should be random numbers in both the rows of array A . I think the random number generator is generating zeros every time. Can somebody help ??
[[0 0 0]
 [0 0 0]]
Run Code Online (Sandbox Code Playgroud)

Ian*_*nhi 6

您构造数组的方式A是它始终具有 integer dtype。您可以使用print(A.dtype). 这意味着 0-1 之间的值被强制转换为 0,这是一个问题,因为np.random.rand只返回 0 和 1 之间的值。您可以通过以下几种方法解决此问题:

  1. 使用浮点数构建 A=np.array([(1.,2.,3.),(4.,5.,6.)])
  2. 显式设置数据类型 A=np.array([(1,2,3),(4,5,6)], dtype=np.float)
  3. 强制转换为浮动类型 A=np.array([(1,2,3),(4,5,6)]).astype(np.float)