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?
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With