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
. So for the given example the result would be r = [True & False, True & True & True, True & True]
. Is there any nice way to do this computation using Numpy?
Since you tagged numpy, you can use list comprehension, numpy.unique and 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:
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.