如何将一系列条件应用于 np.where()



我需要计算来自np.array的相同元素的索引的平均值

我已经尝试过使用 np.where 函数进行映射和列表理解,但它们返回我需要转换回 np.like 的 python 列表。 不幸的是,我自己无法从numpy中找到合适的东西,并且不太了解numpy

有一个例子说明我试图做的事情

A = np.array ([2,5,9,8,8,3,2,1,2,1,8])
set_ = np.unique(A)
indeces = [np.where(A==i) for i in set_]
mean_ = [np.mean(i) for i in indeces]

但是列表理解给出了一个列表,而 np.where - ndarray我想在不进行不必要转换的情况下使用 Numpy

我尝试使用map和np.fromiter,例如:

indeces = map(np.where,[A==i for i in set_])
mean_ = np.fromiter(indeces,dtype = np.int)

但它提供了一个:值错误:使用序列设置数组元素。

mean_ = [8.0, 4.666666666666667, 5.0, 1.0, 5.666666666666667, 2.0]

使用上面的代码,但任何人都可以建议一种有效的方法来纯粹使用 Numpy 或 Closest 来做到这一点。感谢您的关注(

如果 A 中的值是非负整数,则可以通过两次调用来执行计算 np.bincount

import numpy as np
A = np.array ([2,5,9,8,8,3,2,1,2,1,8])
result = np.bincount(A, weights=np.arange(len(A))) / np.bincount(A)
result = result[~np.isnan(result)]
print(result)

收益 率

[8.         4.66666667 5.         1.         5.66666667 2.        ]

如果A包含任意值,则可以先将这些值转换为非负整数标签,然后按上述操作:

import numpy as np
A = np.array ([2,5,9,8,8,3,2,1,2,1,8])+0.5
uniqs, B = np.unique(A, return_inverse=True)
result = np.bincount(B, weights=np.arange(len(B))) / np.bincount(B)
result = result[~np.isnan(result)]
print(result)

收益 率

[8.         4.66666667 5.         1.         5.66666667 2.        ]

工作原理:np.bincount计算非负整数数组中每个值出现的次数:

In [161]: np.bincount(A)
Out[161]: array([0, 2, 3, 1, 0, 1, 0, 0, 3, 1])
                    |  |                 |  |
                    |  |                 |  o--- 9 occurs once
                    |  |                 o--- 8 occurs three times
                    |  o--- 2 occurs three times                       
                    o--- 1 occurs twice

如果提供了 weight 参数,则不是将出现次数计数为 1,而是将计数增加 weight

In [162]: np.bincount(A, weights=np.arange(len(A)))
Out[163]: array([ 0., 16., 14.,  5.,  0.,  1.,  0.,  0., 17.,  2.])
                      |    |                             |     |
                      |    |                             |     o--- 9 occurs at index 2
                      |    |                             o--- 8 occurs at indices (3,4,10)
                      |    o--- 2 occurs at indices (0,6,8)
                      o--- 1 occurs at indices (7,9)

由于 np.arange(len(A)) 等于 A 中每个项目的索引值,因此上述对 np.bincount 的调用对每个值的索引求和,以 A 为单位。将返回的两个数组除以 np.bincount 得到平均索引值。


或者,使用 Pandas,计算可以表示为groupby/mean运算:

import numpy as np
import pandas as pd
A = np.array([2,5,9,8,8,3,2,1,2,1,8])
S = pd.Series(np.arange(len(A)))
print(S.groupby(A).mean().values)

收益 率

[8.         4.66666667 5.         1.         5.66666667 2.        ]

最新更新