简体   繁体   中英

Find local mimimum in 2D np.array in Python

I have this two columns array :

A  | 1 
A  | 2
A  | 3
B  | 4
B  | 5
B  | 6

where A, B are constants. What I want is to find the mimimum value of each parameter A and B, so the result of this operation would be an other 2D array like this one :

A | 1
B | 4

I succeed in finding the mimium when only one constant A is present :

MIN = np.where(arr == np.amin(arr[:,1]))
output = arr[MIN[0],:]
>> output = A | 1

But I can't automatize it when the array is more complex than that. Thanks for the help.

What you are looking for is the optional keyword axis in the function np.min . It allows you to compute the minimum of the array column-wise. The use of np.min is also better than using np.amin since it allows you to perform one less step before the result (you immediately have the minimum instead of its index in the table)

Try this :

import numpy as np

a = np.array([[1,2,3], [4,5,6]])
np.min(a, axis=1)
# Result : array([1, 4])

You can use np.unique for extracting the unique values from the first column and then use a boolean mask along the first axis:

np.stack([(x, a[a[:, 0] == x, 1].min()) for x in np.unique(a[:, 0])])

Alternatively, if you have access to pandas , you can create a DataFrame and use grouby on the first column:

import pandas as pd

result = pd.DataFrame(a).groupby(0).min().values

Code used for example setup of a :

import numpy as np

a = np.array([[1, 1, 1, 2, 2, 2],
              [1, 2, 3, 4, 5, 6]]).T

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM