Search code examples
pythonnumpycombinationspython-itertools

Why I am getting repetitions after calculation in python?


I am executing some simple statements, and I am expecting a single array as my result. But, I am getting 6 rows as a result.

from itertools import combinations
import numpy as np

res = [
    np.array([[12.99632095], [29.60571445], [-1.85595153],
              [68.78926787], [ 2.75185088], [ 2.75204384]]),
    np.array([[ 15.66458062], [ 22.16467595], [ -3.75927882],
              [ -2.65954113], [  2.30128711], [197.45459974]])
]

pairs = combinations(res, 2)
for pair in pairs:
    r = np.concatenate(pair, axis=1)
    r1 = pair[0]
    r2 = pair[1]
    sign = np.sign(r1 * r2)
    result = np.multiply(
        sign,
        np.min(np.abs(r), axis=1) / np.max(np.abs(r), axis=1)
    )

The value of r is like this

[[ 12.99632095  15.66458062]
 [ 29.60571445  22.16467595]
 [ -1.85595153  -3.75927882]
 [ 68.78926787  -2.65954113]
 [  2.75185088   2.30128711]
 [  2.75204384 197.45459974]]

The result I am getting is like this

[[ 0.82966287  0.74866209  0.49369882  0.03866215  0.83626883  0.0139376 ]
 [ 0.82966287  0.74866209  0.49369882  0.03866215  0.83626883  0.0139376 ]
 [ 0.82966287  0.74866209  0.49369882  0.03866215  0.83626883  0.0139376 ]
 [-0.82966287 -0.74866209 -0.49369882 -0.03866215 -0.83626883 -0.0139376 ]
 [ 0.82966287  0.74866209  0.49369882  0.03866215  0.83626883  0.0139376 ]
 [ 0.82966287  0.74866209  0.49369882  0.03866215  0.83626883  0.0139376 ]]

My expected result is something like only one row of the existing result.

[[ 0.82966287  0.74866209  0.49369882  -0.03866215  0.83626883  0.0139376 ]]

Why am I getting repetitions and - result in the 4th row of the existing result output?


Solution

  • You are doing combinations. So, if you have more combinations you also need to append the result.

    results = []
    for pair in pairs:
        r = np.concatenate(pair, axis=1)
        for i in range(len(r)):
            r1 = r[:, 0]
            r2 = r[:, 1]
            sign = np.sign(r1 * r2)
            result = np.multiply(sign, np.min(np.abs(r), axis=1) / np.max(np.abs(r), axis=1))
        results.append(result)
    

    You were lopping the whole combination again and again. Just need to change the value of r1, r2, and a loop.