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

Question:

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:

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

Asked By: guzel6031

||

Answers:

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.

Answered By: MGK