Creating a function taking dataframe as args and return min and max

Question:

My Function

def sort_value(a, b, c, d):
    temp_dict = {
        'a':a,
        'b':b,
        'c':c,
        'd':d
    }
    
    # error => sort_df = dict(sorted(temp_df.items(), key=lambda item: item[1]))
    dict_key = list(temp_df.keys())
    dict_value = list(temp_df.values())

    min = dict_key[0]
    max = dict_key[-1]

    return min, max

df['min'], df['max'] = sort_value(df.a, df.b, df.c, df.d)

ERROR : ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Asked By: Kiran Kumar

||

Answers:

you have typo in accessing the dictionary keys and values,

    dict_key = list(temp_dict.keys())
    dict_value = list(temp_dict.values())
Answered By: Mohamed Shabeer kp

If you are trying to find the min and max of multiple columns, just use built-in pandas functionality:

cols = ['a', 'b', 'c', 'd']
df.loc[:, ['min', 'max']] = df.loc[:, cols].values.min(), df.loc[:, cols].values.max()
Answered By: Plagon

IIUC:

df['min'], df['max'] = df.min(axis=1), df.max(axis=1)
print(df)

# Output
    a   b   c   d  min  max
0   9   8   9   7    7    9
1   2   7  12   2    2   12
2   8   4  12   4    4   12
3  16  11   4  12    4   16
4  12   0   0  14    0   14
5   3  10   9  15    3   15
6  13  17   6   5    5   17
7   3  11  10  19    3   19
8   0  11   6  15    0   15
9   2  11  10   3    2   11

If you want to know the column where the min and the max are stored, use idxmin and idxmax:

df['idxmin'], df['idxmax'] = df.idxmin(axis=1), df.idxmax(axis=1)
print(df)

# Output
    a   b   c   d idxmin idxmax
0   9   8   9   7      d      a
1   2   7  12   2      a      c
2   8   4  12   4      b      c
3  16  11   4  12      c      a
4  12   0   0  14      b      d
5   3  10   9  15      a      d
6  13  17   6   5      d      b
7   3  11  10  19      a      d
8   0  11   6  15      a      d
9   2  11  10   3      a      b
Answered By: Corralien