n_inspring
n_inspring

Reputation: 41

Python: map four arrays

What I want to do is somehow map two 2D arrays. I have two pairs of corresponding arrays:

x1=[1,2,3,4,5]
y1=[7,9,10,17,4]

x2=[3,4,5,6,7]
y2=[5,4,1,13,12]

What I would like my program to do is:

Step 1. compare x1 with x2 and find matching elements

[3,4,5]

Step 2. For those matching elements perform a substraction of matching y-elements:

[y1(x)-y2(x)]=[y1(3)-y2(3), y1(4)-y2(4), y1(5)-y2(5)]

which is the same as: [10-5, 17-4, 4-1]=[5,13,3]

Step 3. Return another two arrays, that has unused elements from x1, y1, x2, y2 and those after substraction. Expected result:

x = [1,2,3,4,5,6,7] y = [7,9,5,13,3,13,12]

Is there an easy way to do something like that, maybe using map()? Those are all separate arrays.

Upvotes: 2

Views: 70

Answers (2)

Samer Ayoub
Samer Ayoub

Reputation: 1001

print( [ y1[x1.index(elt)]-y2[x2.index(elt)] for elt in x1 if elt in x2 ] )

enter image description here

To get all keys, but not very efficient

[ y1[x1.index(elt)]-y2[x2.index(elt)] if elt in x2 else y1[x1.index(elt)] for elt in x1 ]+[ y2[x2.index(elt)] for elt in x2 if elt not in x1 ]

enter image description here Another method for both parts, using dictionaries to be more efficient

d1 = {x:y for x,y in zip(x1,y1)}
d2 = {x:y for x,y in zip(x2,y2)}
d = d2.copy()
d = { k:(d1[k]-v if k in d1 else v) for k,v in d.items() }
res = d1.copy()
res.update(d)
X, Y = list(res.keys()), list(res.values())
print(X, Y, sep="\n")

enter image description here

If you have huge date, then use pandas dataframes

import pandas as pd

df1 = pd.DataFrame({"k":x1, "v1":y1}).set_index("k")
df2 = pd.DataFrame({"k":x2, "v2":y2}).set_index("k")

def f(row):
    a, b = row[0], row[1]
    if a and b:
        return a - b
    elif a:
        return a
    else:
        return b

df = df1.join(other=df2, how="outer").fillna('')
df = pd.DataFrame({"v":df.apply(f, axis=1)} )
print(df)

enter image description here

Upvotes: 1

azro
azro

Reputation: 54168

  1. To get common elements between 2 lists, use set and operator &

    x_common_vals = set(x1) & set(x2)
    print(x_common_vals) #{3, 4, 5}
    
  2. For the substraction operation, for each value you need to get its index in x1 and x2 and get the value at that index in y1 and y2, like y1[x1.index(value)]

    y_sub = list(map(lambda v: y1[x1.index(v)] - y2[x2.index(v)], x_common_vals))
    print(y_sub)  # [5, 13, 3]
    
  3. WorkInProgress

Upvotes: 1

Related Questions