Home > Mobile >  Using .values.max() for arrays
Using .values.max() for arrays

Time:01-27

I use the following code to get a row from a dataframe and then find the max value.

def find_max(a):
    return a.values.max()

row = df.iloc[0].astype(int)
max_value = find_max(a)

That works fine. However, if I pass an array like

ar = [1,2,3]
max_value = find_max(ar)

it doesn't work and I receive AttributeError: 'list' object has no attribute 'values'. How can I use that function for both types?

CodePudding user response:

You'll have to test for the type, or use exception handling, to switch approaches:

def find_max(a):
    if isinstance(a, list):
        return max(list)
    return a.values.max()

or

def find_max(a):
    try:
        return a.values.max()
    except AttributeError:
        # assume a Python sequence
        return max(a)

Which one you pick depends on a few factors:

  • Do you need to support other iterables, like tuples or sets or generators?
  • What is the more common case; the try...except case is faster if the majority of calls pass in a Pandas series.

Another option is to use np.max(), which works on either type:

import numpy as np

def find_max(a):
    return np.max(a)

Note that there is no need to use the .values attribute here!

CodePudding user response:

def find_max(a):
    if isinstance(a, list):
        return max(a)
    elif isinstance(a, pd.DataFrame):
        return a.values.max()
    else:
        print("No max method found for the input type")

CodePudding user response:

Why don't try numpy's integration for that?

import numpy as np

row = df.iloc[0].astype(int)
max_value = np.max(a.values)

ar = [1,2,3]
max_value = np.max(ar)

This way, you don't have to define a function. In general it`s more pythonic to use already existing and well tested functionality from python packages.

  •  Tags:  
  • Related