Home > other >  finding a minimum value with all header values
finding a minimum value with all header values

Time:11-23

I am trying to find a minimum value in a dataframe with all column values.

Sample data:

**Fitness Value MSU Locations   MSU Range** 
1.180694        {17, 38, 15}    2.017782    
1.202132        {10, 22, 39}    2.032507    
1.179097        {10, 5, 38}     2.048932    
1.175793        {27, 20, 36}    1.820395    
1.187460        {33, 10, 34}    1.922506

I am trying to find a minimum value in Fitness Value column and keeping the whole row record. For intance, If I get the minimum value (1.175793), I want to keep its respective header values which are {27, 20, 36} and 1.820395. So, the final output should be:

1.175793           {27, 20, 36}      1.820395

My sample code:

minValue = df_2['Fitness Value'].min()
print("minimum value in column 'y': " , minValue)

Output:

minimum value in column 'y':  1.175793

I also tried this code:

df_y = pd.DataFrame ()
df_y = df_2.loc[[df_2['Fitness Value']].min()

How can I get an output like this?

1.175793           {27, 20, 36}      1.820395

CodePudding user response:

Use Series.idxmin for indices by minimal values, select row by DataFrame.loc for get row first minimal value in Fitness Value column:

df = df_2.loc[[df_2['Fitness Value'].idxmin()]]
print (df)
   Fitness Value MSU Locations  MSU Range
3       1.175793    {27,20,36}   1.820395

CodePudding user response:

Use min with boolean indexing:

df.loc[df['Fitness Value'].eq(df['Fitness Value'].min())]

Output:

   Fitness Value MSU Locations  MSU Range
3       1.175793  {27, 20, 36}   1.820395

NB. the difference between my answer and that of @jezrael lies in the handling of duplicates in "Fitness Value". Mine keeps all rows with the min, idxmin keeps only the first min. To adapt, depending on what you want.

CodePudding user response:

A solution using your minValue variable.

df[df["Fitness Value"]==minValue]
  • Related