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,050 points
38 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,500 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 ariaholic
• 7,320 points
1,006 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
• 56,140 points
133 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,710 points
42 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 in Python by Mohammad
• 1,400 points
16 views
0 votes
0 answers

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

can you give an example? with the ...READ MORE

May 6 in Python by Waseem
• 2,670 points
8 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,710 points
41 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,710 points
51 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,320 points
49 views
0 votes
1 answer

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.