PedroBiel
PedroBiel

Reputation: 509

Python: Compare two lists and get max and min values with signs

I have two lists of lists. One with maximum values, the other with mínimum values:

list_max = [
    [100, 10, 100],
    [-50, 90, -50]
    ]
list_min = [
    [50, -90, -50],
    [-100, -10, -500]
    ]

I want to get a third list with the maximum absolute values and their signs for each related item, that is:

list_max[0][0] = 100; list_min[0][0] = 50  -> list_3[0][0] = 100
list_max[0][1] = 10;  list_min[0][1] = -90 -> list_3[0][1] = -90

list_3 = [
    [100, -90, 100],
    [-100, 90, -500]
]

Maybe with pandas?

Upvotes: 5

Views: 3280

Answers (4)

L3viathan
L3viathan

Reputation: 27323

You don't need pandas:

list_3 = [
    [max((x, y), key=abs) for x, y in zip(line_max, line_min)]
    for line_max, line_min in zip(list_max, list_min)
]

The trick is zip, and max with the key function abs.

If the absolutes are ever equal (e.g. -50 vs. 50), this solution will prefer the positive value (because abs takes the first maximum value). If the opposite is required, swap x and y in the call to max.

Upvotes: 10

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

numpy one-liner:

import numpy as np

In [1023]: list_max = np.array([
      ...:     [100, 10, 100],
      ...:     [-50, 90, -50]
      ...:     ])
      ...: list_min = np.array([
      ...:     [50, -90, -50],
      ...:     [-100, -10, -500]
      ...:     ])
      ...:     

In [1024]: np.where(np.abs(list_max) > np.abs(list_min), list_max, list_min)
Out[1024]: 
array([[ 100,  -90,  100],
       [-100,   90, -500]])

Upvotes: 3

Jeremy H
Jeremy H

Reputation: 423

Are the lists within list_max and list_min always of the same length? Are list_max and list_min always the same length?

If so, you you can loop through list_max (or list_min) with an index i and loop through the lists within list_max with an index j, finding the max absolute values for each i, j.

list_3 = []

# Loop through lists in list_max
for i in range(len(list_max)):
    temp_list = []
    # Loop through items in each list in list_max
    for j in range(len(list_max[i])):
        list_max_val = list_max[i][j]
        list_min_val = list_min[i][j]
        final_val = list_max_val if abs(list_max_val) > abs(list_min_val) else list_min_val

        # Add value to temporary list
        temp_list.append(final_val)
    # Add the temporary list to list_3
    list_3.append(temp_list)

Edit: Had to modify this as I missed the instruction to keep the sign of the value

Upvotes: 2

Miquel Vande Velde
Miquel Vande Velde

Reputation: 184

As L3viathan shows, you don't need pandas. But just for reference, with pandas you could have done:

import pandas as pd

list_max = pd.DataFrame([
    [100, 10, 100],
    [-50, 90, -50]
])
list_min = pd.DataFrame([
    [50, -90, -50],
    [-100, -10, -500]
])

list_3 = list_max.where(abs(list_max) > abs(list_min), list_min)

Upvotes: 4

Related Questions