upio_4
upio_4

Reputation: 73

How do I stop decimals changing to integers when replacing the numbers of a row in an array?

I'm trying to replace the 0th row of array "A" with 0.5 times the 1st row plus the original 0th row with the code below:

A = np.array([[ 9,  6,  7,  8,  1,  7,  2], [ 8,  2,  6,  5,  1,  5,  3], [ 7,  3,  1,  4,  5, 10,  1],
              [10,  5,  7,  5,  4,  6,  2], [ 5,  5,  2,  6,  4,  2,  7]])
b = A[0]+0.5*A[1]
print(b)
for n in range(len(A[0])):
    A[0][n] = b[n]
A

The list "b" is what I want to replace the old 0th row with. However, in the new version of array A, it takes the list of decimals "b" and makes them integers but I want them to stay as decimals:

[13.   7.  10.  10.5  1.5  9.5  3.5]

array([[13,  7, 10, 10,  1,  9,  3],
       [ 8,  2,  6,  5,  1,  5,  3],
       [ 7,  3,  1,  4,  5, 10,  1],
       [10,  5,  7,  5,  4,  6,  2],
       [ 5,  5,  2,  6,  4,  2,  7]])

How do I make it so the new row's numbers stay as decimal numbers?

Upvotes: 0

Views: 276

Answers (1)

Pablo C
Pablo C

Reputation: 4761

The problem is A's original dtype is int, then every value in it is and will be an int. To fix it, you can specify dtype = float from the beginning:

A = np.array([[ 9,  6,  7,  8,  1,  7,  2],
       [ 8,  2,  6,  5,  1,  5,  3],
       [ 7,  3,  1,  4,  5, 10,  1],
       [10,  5,  7,  5,  4,  6,  2],
       [ 5,  5,  2,  6,  4,  2,  7]], dtype = float)

A[0] += A[1]/2

Output

A
array([[13. ,  7. , 10. , 10.5,  1.5,  9.5,  3.5],
       [ 8. ,  2. ,  6. ,  5. ,  1. ,  5. ,  3. ],
       [ 7. ,  3. ,  1. ,  4. ,  5. , 10. ,  1. ],
       [10. ,  5. ,  7. ,  5. ,  4. ,  6. ,  2. ],
       [ 5. ,  5. ,  2. ,  6. ,  4. ,  2. ,  7. ]])

Upvotes: 2

Related Questions