finding a minimum value with all header values

finding a minimum value with all header values

Problem Description:

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 – 1

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

If need list without columns:

L = df_2.loc[df_2['Fitness Value'].idxmin()].tolist()

If need loop:

out = []
for x in range(0, 2, 1): 
    new_generation = genetic_algorithm(initial_pop_chromosome_fitness)   
    initial_pop_chromosome_fitness = new_generation

    #create Series and append to list of Series out
    s = df_2.loc[df_2['Fitness Value'].idxmin()]
    out.append(L)

df = pd.DataFrame(out)

 

Solution – 2

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.

Solution – 3

A solution using your minValue variable.

df[df["Fitness Value"]==minValue]
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject