Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 852
PedroBiel Avatar asked Aug 02 '19 08:08

PedroBiel


2 Answers

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.

like image 56
L3viathan Avatar answered Oct 12 '22 00:10

L3viathan


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)
like image 29
Miquel Vande Velde Avatar answered Oct 12 '22 01:10

Miquel Vande Velde