I have two columns in my pandas DataFrame.
A B
0 1 5
1 2 3
2 3 2
3 4 0
4 5 1
I need the value in A where the value of B is minimum. In the above case my answer would be 4 since the minimum B value is 0.
Can anyone help me with it?
To find the minimum in column B, you can use
df.B.min()
. For your DataFrame this returns0
.To find values at particular locations in a DataFrame, you can use
loc
:So here,
loc
picks out all of the rows where column B is equal to its minimum value (df.B == df.B.min()
) and selects the corresponding values in column A.This method returns all values in A corresponding to the minimum value in B. If you only need to find one of the values, the better way is to use
idxmin
as @aus_lacy suggests.Here's one way:
idxmin()
returns the index of the minimum value within columnB
. You then locate the value at that same index in columnA
.or if you want a single, albeit less readable, line you can do it like:
Also, as a disclaimer this solution assumes that the minimum value in column
B
is unique. For example if you were to have a data set that looked like this:My solution would return the first instance where
B
's minimum value is located which in this case is in the third row and has a correspondingA
value of3
. If you believe that the minimum value ofB
is not unique then you should go with @ajcr's solution.