Home > front end >  Creating a function taking dataframe as args and return min and max
Creating a function taking dataframe as args and return min and max

Time:01-13

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 = min(dict_value)
    max = max(dict_value)

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

CodePudding user response:

you have typo in accessing the dictionary keys and values,

    dict_key = list(temp_dict.keys())
    dict_value = list(temp_dict.values())

CodePudding user response:

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()

CodePudding user response:

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