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,090 points
1,593 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,560 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,460 points
10,673 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
• 58,020 points
11,713 views
0 votes
2 answers

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

n=[1,2,3,4,5,6,7,8,9] print(len(n)) =9 READ MORE

answered Dec 10, 2020 in Python by anonymous
1,485 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,230 points
1,199 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, 2020 in Python by VJ_python
812 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
3,358 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, 2020 in Python by Niroj
• 82,840 points
957 views
0 votes
1 answer

How do I get the number of elements in a list?

Hello, The len() function can be used with several different ...READ MORE

answered Nov 18, 2020 in Python by Niroj
• 82,840 points
654 views
+1 vote
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP