I am doing this as shown below. Initially I have a 2D array A = [(1,2,3) , (4,5,6)]. Now through a function func , I want to replace all the elements in both the two rows of array A by random numbers. I am trying but I am getting every element as 0 after execution of the function. Can somebody help. Remember I have to do this problem by using this function func and doing these slicing operations.
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)
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]]
The way you are constructing the array A
is such that it will always have integer dtype. You can check with print(A.dtype)
. This means that values that are between 0-1 are getting cast to zero which is a problem because np.random.rand
only returns values between 0 and 1. You can fix this in a few ways:
A=np.array([(1.,2.,3.),(4.,5.,6.)])
A=np.array([(1,2,3),(4,5,6)], dtype=np.float)
A=np.array([(1,2,3),(4,5,6)]).astype(np.float)
The issue is that A
is an array of integers, and np.random.random
generates floats that are less than one for practical purposes. Casting such a number to integer always yields zero.
You can fix in one of two ways:
Make A
an array of float
dtype:
a. A = np.array([[1.0, 2, 3], [4, 5, 6]])
b. A = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)
c. etc...
Generate random integers instead of floats, or at least floats that would cast to nonzero integers:
a. B[:]= np.random.randint(256, size=B.shape)
b. B[:]= np.random.random(B.shape) * 256
c. etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With