mb567
mb567

Reputation: 681

Reduce multiplte arrays based on coordinate values

I have 5 lists:

X = [0,1,2,3,4,0,1,2,3,6]
Y = [9,8,7,6,4,9,4,7,6,3]
R = [1,2,3,4,5,6,7,8,9,0]
P = [2,4,6,8,10,12,14,16,18,20]
Q = [1,3,5,7,9,11,13,15,17,19]

Given duplicate coordinates I want to sum the attributes that refer to the coordinates so for example X[0] = 0 and Y[0] = 9 this point is repeated at X[5] and Y[5] but with different R, P, Q values R[0] != R[5] and so on.

I am trying to produce a list with unique coordinate and summed values of the duplicate coordinates to produce new X, Y, R, P, Q that look like this:

X = [0,1,2,3,4,1,6]
Y = [9,8,7,6,4,4,3]
R = [7,2,11,13,5,7,0]
P = [14,4,22,26,10,14,20]
Q = [14,3,20,24,9,11,19]

I am not able to formulate this problem, any help is appreciated!

Upvotes: 2

Views: 33

Answers (2)

kuzand
kuzand

Reputation: 9806

Here's another solution using Numpy:

import numpy as np

X = np.array([0,1,2,3,4,0,1,2,3,6])
Y = np.array([9,8,7,6,4,9,4,7,6,3])
R = np.array([1,2,3,4,5,6,7,8,9,0])
P = np.array([2,4,6,8,10,12,14,16,18,20])
Q = np.array([1,3,5,7,9,11,13,15,17,19])


coords = np.array(list(zip(X,Y)), dtype=[('f0', '<i4'), ('f1', '<i4')])
unique_coords = np.unique(coords)

X_new = [x[0] for x in unique_coords]
Y_new = [y[1] for y in unique_coords]
R_new = [np.sum(R[coords == coo]) for coo in unique_coords]
P_new = [np.sum(P[coords == coo]) for coo in unique_coords]
Q_new = [np.sum(Q[coords == coo]) for coo in unique_coords]

print(X_new)
print(Y_new)
print(R_new)
print(P_new)
print(Q_new)

Output:

[0, 1, 1, 2, 3, 4, 6]
[9, 4, 8, 7, 6, 4, 3]
[7, 7, 2, 11, 13, 5, 0]
[14, 14, 4, 22, 26, 10, 20]
[12, 13, 3, 20, 24, 9, 19]

Upvotes: 0

zipa
zipa

Reputation: 27879

If you use pandas it would look like this:

import pandas as pd

X = [0,1,2,3,4,0,1,2,3,6]
Y = [9,8,7,6,4,9,4,7,6,3]
R = [1,2,3,4,5,6,7,8,9,0]
P = [2,4,6,8,10,12,14,16,18,20]
Q = [1,3,5,7,9,11,13,15,17,19]

df = pd.DataFrame([X, Y, R, P, Q])
X, Y, R, P, Q = df.T.groupby([0,1]).sum().reset_index().T.values

Which would produce:

[0 1 1 2 3 4 6]
[9 4 8 7 6 4 3]
[ 7  7  2 11 13  5  0]
[14 14  4 22 26 10 20]
[12 13  3 20 24  9 19]

Take note that order is not preserved but numbers match.

Upvotes: 1

Related Questions