Home > Net >  Inverting numbers in python
Inverting numbers in python

Time:03-19

I have an array of lists, I want to invert the numbers, all negative numbers should be positive and vice versa.

array([[-0.16759927, -0.04342834,  0.9848982 ],
       [-0.45425025,  0.47425876,  0.75414544],
       [ 0.14613204, -0.19651204,  0.96955064],
       [ 0.55392107,  0.80368964,  0.21738078],
       [-0.13777969, -0.14350102,  0.98001235],
       [-0.00225069,  0.00356328,  0.99999112]])

Is there a python way to do this?

CodePudding user response:

You can just do -array and get the desired result.

CodePudding user response:

Inverting a number is not switching if a number is positive or negative. It is flipping a fraction upside down. Every number is just the number over one, so you just have to divide one by each number. This should do that:

import numpy as np
array = np.array([[-0.16759927, -0.04342834,  0.9848982 ],
       [-0.45425025,  0.47425876,  0.75414544],
       [ 0.14613204, -0.19651204,  0.96955064],
       [ 0.55392107,  0.80368964,  0.21738078],
       [-0.13777969, -0.14350102,  0.98001235],
       [-0.00225069,  0.00356328,  0.99999112]])
new_array = np.array([1/i for i in array])

Value for new_array:

array([[  -5.9666131 ,  -23.0264385 ,    1.01533336],
       [  -2.20142972,    2.10855357,    1.32600417],
       [   6.84312626,   -5.08874673,    1.03140564],
       [   1.80531136,    1.2442614 ,    4.60022271],
       [  -7.25796378,   -6.96859158,    1.0203953 ],
       [-444.30818993,  280.64030893,    1.00000888]])

But if you just want what you described this should work:

import numpy as np
array = np.array([[-0.16759927, -0.04342834,  0.9848982 ],
       [-0.45425025,  0.47425876,  0.75414544],
       [ 0.14613204, -0.19651204,  0.96955064],
       [ 0.55392107,  0.80368964,  0.21738078],
       [-0.13777969, -0.14350102,  0.98001235],
       [-0.00225069,  0.00356328,  0.99999112]])
new_array = -array

Value for new_array:

array([[ 0.16759927,  0.04342834, -0.9848982 ],
       [ 0.45425025, -0.47425876, -0.75414544],
       [-0.14613204,  0.19651204, -0.96955064],
       [-0.55392107, -0.80368964, -0.21738078],
       [ 0.13777969,  0.14350102, -0.98001235],
       [ 0.00225069, -0.00356328, -0.99999112]])
  • Related