[英]Grouping two vectors using Numpy
I have two vectors w = [1, 1, 2, 2, 2, 3, 3]
and a = [True, False, True, True, True, True, True]
and I want to group by the numbers in w
to compute the conjunction of the selected in a
.我有两个向量
w = [1, 1, 2, 2, 2, 3, 3]
和a = [True, False, True, True, True, True, True]
我想按w
中的数字分组到计算 a 中选定项的a
。 So for the given example the result would be r = [True & False, True & True & True, True & True]
.因此,对于给定的示例,结果将是
r = [True & False, True & True & True, True & True]
。 Is there any nice way to do this computation using Numpy?有没有使用 Numpy 进行此计算的好方法?
Since you tagged numpy, you can use list comprehension, numpy.unique and numpy.all :由于您标记了 numpy,您可以使用列表理解、 numpy.unique和numpy.all :
import numpy as np
w = np.array([1, 1, 2, 2, 2, 3, 3])
a = np.array([True, False, True, True, True, True, True])
r = [np.all(a[w==i]) for i in np.unique(w)]
r
[False, True, True]
Alternatively if you have pandas dependency:或者,如果您有 pandas 依赖项:
import pandas as pd
df = pd.DataFrame({'w':w, 'a':a})
r = df.groupby('w').agg(np.all).reset_index()
r
w a
0 1 False
1 2 True
2 3 True
This can be done with a simple list comprehension:这可以通过一个简单的列表理解来完成:
>>> [all(a[np.where(w == i)]) for i in np.unique(w)]
[False, True, True]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.