0

I have a data frame of 15000 record which has text column (column name = clean) as a list, please refer below

enter image description here

I need to find the minimum value in each row and add as a new column called min


def find_min(x):
    x = min(x)
    return(x)

I tried to pass the above function


df1['min'] = df1['clean'].map(find_min)

Getting below error

ValueError: min() arg is an empty sequence

It seems there is an empty list, how to address this as I am having 15000 records Please advise

4
  • your function is named min, so you no longer have access to the builtin min function in the current scope. Try renaming your outer function. Btw you could just do df1['clean'].map(min) without having to define a min function.
    – cs95
    Feb 16, 2021 at 7:47
  • 1: there's a built-in function called min already. 2: you're overwriting it. 3: you're calling min(x) from within the function itself, resulting in an infinite recursion.
    – ddejohn
    Feb 16, 2021 at 7:47
  • @cs95. I tried. Getting this error "ValueError: min() arg is an empty sequence". Type of my column in pd.series.
    – sthambi
    Feb 16, 2021 at 7:58
  • That kinda makes sense, if the list is empty, min([]) makes no sense. Btw that's a different question from the one currently being asked, so maybe update your post.
    – cs95
    Feb 16, 2021 at 7:58

1 Answer 1

1

Since we have a list of columns, let us try handling errors in your function using try/except (EAFP pattern):

def find_min(x):
    try: 
        return min(x)
    except ValueError:
        return np.nan

df1['min'] = df1['clean'].map(find_min)

Another way is to skip the function and define this inline:

df1['min'] = df1['clean'].map(lambda x: min(x) if len(x) else np.nan)

You can also do this using a list comprehension, which is quite fast:

df1['min'] = [find_min(x) for x in df1['clean']]

or,

df1['min'] = [min(x) if len(x) else np.nan for x in df1['clean']]
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.