我有5个列表:
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]
给出重复的坐标,我想对引用坐标的属性求和,因此例如X [0] = 0和Y [0] = 9,此点在X [5]和Y [5]处重复,但有不同R,P,Q值R [0]!= R [5],依此类推。
我正在尝试生成具有唯一坐标和重复坐标总和的列表,以生成新的X,Y,R,P,Q,如下所示:
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]
我无法提出这个问题,感谢您的帮助!
答案 0 :(得分:1)
如果您使用熊猫,它将如下所示:
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
哪个会产生:
[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]
请注意,订单不会保留,但数字会匹配。
答案 1 :(得分:0)
这里是使用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)
输出:
[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]