pythonpandasdataframegenetic-algorithmgenetic-programming

finding a minimum value with all header values


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

Solution

  • 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.