Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

write a def() function to fetch all minimum values along rows from multiple cols

I want to write a function to find minimum value of all rows from all 4 columns and to store this single value in new column of dataframe.
Please write a full code and not in explanations

Easy sample:

| a      | b    | c   | d  |
| ------ | ---- | --- |----|
| 20     | 29   | 32  |31  |
| 30     | 12   | 56  |25  |
| 38     | 25   | 19  |32  |

I want:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

| a      | b    | c   | d  | min_value
| ------ | ---- | --- |----|---------
| 20     | 29   | 32  |31  | 20
| 30     | 12   | 56  |25  | 12
| 38     | 25   | 19  |32  | 19

I have tried this code and it seems to be incomplete or wrong.
Do explain why and write code for explanation.

def values():
    s1 = df['a']
    s2 = df['b']
    s3 = df['c']
    s4 = df['d']
return (s1,s2,s3,s4).min()

def minimum():
    obj = values()
    print (obj[0])


df['min_value'] = minimum()

I am getting this error:

'tuple' object has no attribute 'min'

I dont want to simply use min(). Instead write a function to do it.

>Solution :

Here is a function that you can use to get the minimum value for each row from all 4 columns:

def get_min_values(df):
    min_values = []
    for index, row in df.iterrows():
        min_value = min(row['a'], row['b'], row['c'], row['d'])
        min_values.append(min_value)
    return min_values

df['min_value'] = get_min_values(df)

This function first creates an empty list called min_values to store the minimum values for each row. It then iterates through the rows of the DataFrame using iterrows(). For each row, it gets the minimum value from the 4 columns a, b, c, and d, using the min() function. It then appends the minimum value to the min_values list. Finally, the function returns the min_values list, which can then be used to create a new column in the DataFrame.

You can then use this function as follows:

df['min_value'] = get_min_values(df)

This will create a new column in the DataFrame called min_value and populate it with the minimum values for each row.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading