python - 如何将一系列条件应用于 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)
但它提供了一个: ValueError: setting an array element with a sequence。
mean_ = [8.0, 4.666666666666667, 5.0, 1.0, 5.666666666666667, 2.0]
使用上面的代码,但是任何人都可以建议一种有效的方法来使用 numpy 或最接近的方式来完成此操作。感谢关注)
解决方案
如果 中的值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. ]
推荐阅读
- javascript - Axios 没有通过反应 js 返回响应
- excel - 从表中提取部分匹配
- java - 自定义注释以修改值
- javascript - 在 DIV 中滚动音频
- java - 如果 Lombok RequiredArgsConstructor 和 @Autowired 都注入了 bean,我应该如何模拟我的课程?
- ios - Flutter MaterialPageRoute 不会在原生 iOS navigatorViewController 上导航
- selenium-webdriver - 在机器人框架中,我无法在 material-ui 日历中获取定位器
- office-js - 如何更改右侧任务窗格选项卡上的图标
- flutter - 更新后 Gradle 无法正常工作 · Issue #25820
- intellij-idea - intellij idea 在 Ubuntu18.04 打不开