Skip to main content
 首页 » 编程设计

python之用 numpy/pandas 中的组聚合替换组的值

2024年10月24日8落叶无声

我在 numpy 数组 X 中有一个图像:

array([[ 0.01176471,  0.49019608,  0.01568627], 
       [ 0.01176471,  0.49019608,  0.01568627], 
       [ 0.00784314,  0.49411765,  0.00784314], 
       ...,  
       [ 0.03921569,  0.08235294,  0.10588235], 
       [ 0.09411765,  0.14901961,  0.18431373], 
       [ 0.10196078,  0.15294118,  0.21568627]]) 

我在这个数组上运行了一个聚类算法来找到相似的颜色,并为每个像素 Y 设置了另一个包含类的数组:

array([19, 19, 19, ..., 37, 20, 20], dtype=int32) 

将集群中所有像素的颜色替换为该集群上的平均值的最快、最漂亮和最 pythonistic 的方法是什么?

我想出了以下代码:

import pandas as pd 
import numpy as np 
<...> 
df = pd.DataFrame.from_records(X, columns=list('rgb')) 
df['cls'] = Y 
mean_colors = df.groupby('cls').mean().values 
# as suggested in comments below 
# for cls in range(len(mean_colors)): 
#    X[Y==cls] = mean_colors[cls] 
X = mean_colors[Y] 

有没有办法只在 pandas 或 numpy 中做到这一点?

请您参考如下方法:

假设所有标签都在 Y 中,您可以使用 basic-indexing -

mean_colors[Y] 

对于多次索引到同一位置的情况,为了提高性能,您还可以使用 np.take而不是像这样的纯索引 -

np.take(mean_colors,Y,axis=0) 

运行时测试-

In [107]: X = np.random.rand(10000,3) 
 
In [108]: Y = np.random.randint(0,100,(10000)) 
 
In [109]: np.allclose(np.take(mean_colors,Y,axis=0),mean_colors[Y]) 
Out[109]: True           # Verify approaches 
 
In [110]: %timeit mean_colors[Y] 
1000 loops, best of 3: 280 µs per loop 
 
In [111]: %timeit np.take(mean_colors,Y,axis=0) 
10000 loops, best of 3: 63.7 µs per loop