Numpy 删除具有附加要求的重复项

Numpy 删除具有附加要求的重复项,numpy,duplicates,unique,Numpy,Duplicates,Unique,我有三列(x,y,m),其中x和y是坐标,m是测量值。有些重复项被定义为相同的(x,y)。在这些复制品中,我然后根据测量值m对它们进行排序,我只选择其中一个最小m的复制品。以下是一个例子: x = np.array([1,1,2,2,1,1,2]) y = np.array([1,2,1,2,1,1,1]) m = np.array([10,2,13,4,6,15,7]) 有三个具有相同坐标的副本(1,1),其中最小m为6。有两个具有相同坐标的副本(2,1),其中最小m为7。所以我想要的最终结

我有三列
(x,y,m)
,其中
x
y
是坐标,
m
是测量值。有些重复项被定义为相同的
(x,y)
。在这些复制品中,我然后根据测量值
m
对它们进行排序,我只选择其中一个最小
m
的复制品。以下是一个例子:

x = np.array([1,1,2,2,1,1,2])
y = np.array([1,2,1,2,1,1,1])
m = np.array([10,2,13,4,6,15,7])
有三个具有相同坐标的副本
(1,1)
,其中最小
m
为6。有两个具有相同坐标的副本
(2,1)
,其中最小
m
为7。所以我想要的最终结果是:

x = np.array([1,2,1,2])
y = np.array([2,2,1,1])
m = np.array([2,4,6,7])

numpy.unique
无法处理这种情况。有什么好主意吗

您可以尝试以下方法:

import collections
x = np.array([1,1,2,2,1,1,2])
y = np.array([1,2,1,2,1,1,1])
m = np.array([10,2,13,4,6,15,7])
coords = [str(x[i]) + ',' + str(y[i]) for i in range(len(x))]
results = collections.OrderedDict()
for coords, m in zip(coords, m):
    if coords not in results:
        results[coords] = m
    else:
        if m < results[coords]:
            results[coords] = m
x = np.array([int(key.split(',')[0]) for key, _ in results.items()])
y = np.array([int(key.split(',')[1]) for key, _ in results.items()])
m = np.array([value for _, value in results.items()])
导入集合
x=np.数组([1,1,2,2,1,1,2])
y=np.数组([1,2,1,2,1,1,1])
m=np.数组([10,2,13,4,6,15,7])
coords=[str(x[i])+','+str(y[i])表示范围(len(x))内的i]
结果=collections.OrderedDict()
对于coords,邮政编码为m(coords,m):
如果结果不一致:
结果[coords]=m
其他:
如果m<结果[coords]:
结果[coords]=m
x=np.array([int(key.split(',')[0]),用于键,在results.items()中)
y=np.array([int(key.split(',')[1]),用于键,在results.items()中)
m=np.array([value for x,value in results.items()]))

我们可以在这里使用熊猫作为更清洁的解决方案-

import pandas as pd

In [43]: df = pd.DataFrame({'x':x,'y':y,'m':m})

In [46]: out_df = df.iloc[df.groupby(['x','y'])['m'].idxmin()]

# Format #1 : Final output as a 2D array
In [47]: out_df.values
Out[47]: 
array([[1, 1, 6],
       [1, 2, 2],
       [2, 1, 7],
       [2, 2, 4]])

# Format #2 : Final output as three separate 1D arrays
In [50]: X,Y,M = out_df.values.T

In [51]: X
Out[51]: array([1, 1, 2, 2])

In [52]: Y
Out[52]: array([1, 2, 1, 2])

In [53]: M
Out[53]: array([6, 2, 7, 4])

谢谢@Divakar,我运行了你的命令,得到了几乎相同的结果。唯一的区别是,当我运行
out_df.values
时,
m
列位于第一列。我想知道为什么会有这样的差异?@HuanianZhang是的,排序是基于dataframe如何构造头的。解决订单问题的一种方法是使用类似
idx=df.groupby(['x','y'])['m'].idxmin().values
,然后使用
idx
x,y,m
中选择值。谢谢@Divakar,我也通过上面的命令找到了它。谢谢@ashemag。