2

I have the following numpy arrays:

X = np.array([[1,2,3], [4,5,6], [7,8,9]])
y = np.array([[0.1,0.2,0.3], [0.4,0.5,0.743], [0.834,0.96,0.1]])

I was trying to copy some columns in y into X using the following:

X[:, [0,1]] = y[:, [0,1]]

However after I print X I get:

In[20]: X
Out[20]: 
array([[0, 0, 3],
       [0, 0, 6],
       [0, 0, 9]])

As you can see, as if the floats are rounded. I want the floats as is without rounding, how can I fix that ?

1 Answer 1

1

The dtype of x is int as it has all integer values,

so just change the dtype while creating x as below:

x = np.array([[1,2,3], [4,5,6], [7,8,9]], dtype=float)
y = np.array([[0.1,0.2,0.3], [0.4,0.5,0.743], [0.834,0.96,0.1]])

x[:, [0,1]] = y[:, [0,1]]

print(x)

Output:

[[0.1   0.2   3.   ]
 [0.4   0.5   6.   ]
 [0.834 0.96  9.   ]]

Edit

Or if you dont create x manually then as @Arda Keskiner suggested in comments use:

x = x.astype(float)
x[:, [0,1]] = y[:, [0,1]]
Sign up to request clarification or add additional context in comments.

2 Comments

Correct answer. What you can also do is define X and then change it's type to float by using .astype(float) . X = np.array([[1,2,3], [4,5,6], [7,8,9]]).astype(float)
That's useful when you are getting value from some source and don't have control over it. But if you are creating array then using dtype parameter is effcient as there is overhead for calling a methd astype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.