In NumPy how do I get the maximum of subsets? Python

0 votes

I have an array of values, said v, (e.g. v=[1,2,3,4,5,6,7,8,9,10]) and an array of indexes, say g(e.g. g=[0,0,0,0,1,1,1,1,2,2]).

I know, for instance, how to take the first element of each group, in a very numpythonic way, doing:

import numpy as np
v=np.array([1,2,3,4,74,73,72,71,9,10])
g=np.array([0,0,0,0,1,1,1,1,2,2])
mask=np.concatenate(([True],np.diff(g)!=0))
v[mask]

returns:

array([1, 74, 9])

Is there any numpythonic way (avoiding explicit loops) to get the maximum of each subset?

Nov 9, 2018 in Python by Anirudh
• 2,080 points
299 views

1 answer to this question.

0 votes

You can use np.maximum.reduceat:

>>> _, idx = np.unique(g, return_index=True)
>>> np.maximum.reduceat(v, idx)
array([ 4, 74, 10])
answered Nov 9, 2018 by Nymeria
• 3,520 points

Related Questions In Python

0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by aryya
• 7,380 points
8,769 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

What i found is that you can use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 57,680 points
4,141 views
0 votes
1 answer

How can I get the count of a list in Python?

len() >>> mylist=[] >>> print len(mylist) 0 READ MORE

answered Dec 12, 2018 in Python by charlie_brown
• 7,780 points
266 views
0 votes
1 answer

how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

answered Mar 12, 2019 in Python by Mohammad
• 3,210 points
234 views
0 votes
1 answer

how do i get the list of all the keys in my dictionary?

my_dict = {'one': 'first', 'two': 'second', 'three': ...READ MORE

answered Sep 30 in Python by VJ_python
59 views
+1 vote
1 answer

how do i get a optimal cutoff value(directly in the form of numeric) from roc curves?

The optimal CutOff value is the point ...READ MORE

answered Oct 17, 2019 in Python by Saira
799 views
0 votes
1 answer

how do i get anova table of split plot design or factorial experimental design in python?

Hello @ kapil, For your query you can refer ...READ MORE

answered Aug 24 in Python by Niroj
• 66,340 points
126 views
0 votes
1 answer

How can I compare the content of two files in Python?

Assuming that your file unique.txt just contains ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,780 points
1,016 views
+1 vote
1 answer