Search code examples
pythonarraysnumpynormalize

Normalize the elements of columns in an array to 1 or -1 depending on their sign


I want to normalize the elements of columns in array ‘x’, which contains both positive and negative numbers, to -1, or 1.

Negative elements of x should be normalized to x.min of each column where x.min becomes - 1, and positive elements of x should be normalized to x.max of each column where x.max becomes 1. Zero values should remain zero.

I can get part of the way there using:

x = np.array([[ 1,  3,  1  ],
              [-2, -5, -0.5],
              [-3, -1,  1.5],   
              [ 2,  7,  2  ]])

x_norm = x / x.max(axis=0)

print(x_norm)
[[ 0.5         0.42857143  0.5       ]
 [-1.         -0.71428571 -0.25      ]
 [-1.5        -0.14285714  0.75      ]
 [ 1.          1.          1.        ]]

But really I want the result to be:

print(x_norm)
[[ 0.5         0.42857143  0.5       ]
 [-0.66       -1.         -1.        ]
 [-1.         -0.2         0.75      ]
 [ 1.          1.          1.        ]]

Solution

  • You can check the condition with np.where and apply two different normalizations based on the condition:

    np.where(x<0, -x / x.min(axis=0), x / x.max(axis=0))
    Out[6]: 
    array([[ 0.5       ,  0.42857143,  0.5       ],
           [-0.66666667, -1.        , -1.        ],
           [-1.        , -0.2       ,  0.75      ],
           [ 1.        ,  1.        ,  1.        ]])