I write a simple code list below:
data = np.array([[1,1,1],[2,3,4]])
xdata = [i 0.1 for i in data[0]]
print(xdata)
data[0] = xdata
print(data)
But the result I get in console i
[1.1, 1.1, 1.1]
[[1 1 1]
[2 3 4]]
While I expect it to be
[1.1, 1.1, 1.1]
[[1.1 1.1 1.1]
[2 3 4]]
Why I can't change the value in NumPy array this way?
CodePudding user response:
Create your array like this
data = np.array([[1,1,1],[2,3,4]], type=np.float64)
and it should work. Since you create the array with only integers, its data type becomes np.int64, which means that it can only hold integers.
CodePudding user response:
Your code works mostly as expected with one little problem:
This line
data = np.array([[1,1,1],[2,3,4]])
create a numpy-array of type int, and hence this line
data[0] = xdata
needs to truncate everything behind the decimal point. If you create a float array like this:
data = np.array([[1,1,1],[2,3,4]], dtype=float)
everything will work, as expected. However, if you just want to add to the first row 0.1 a nicer complete solution of your code is:
data = np.array([[1,1,1],[2,3,4]], dtype=float)
data[0] = 0.1
no list comprehension needed.