TransWikia.com

ValueError: ('The truth value of a Series is ambiguous after applying if/else condition in Pandas data frames

Data Science Asked by Malathi on August 14, 2021

I want to create a new variable for the dataframe details called lower after iterating through multiple data frames.

  • list1 is a list of string values of a column named variable_name in the details.
  • vars_df is another data frame with 2 columns, namely variable_name and direction. Both columns contain with string values. vars_df.shape = (19,2)
    Some values of variable_name in vars_df are present in list1 as well as data_set.
    data_set.shape = (32,107).df.shape = (96,1)

The following code, which aims to do the above:

    def get_value(df,list1):
        if ((vars_df['variable_name']) in list1) & (vars_df['direction'] =='up'):
            data = data_set[df['variable_name']]
        else:
            data = data_set[df['variable_name']]-20
            if data < 0:
               data = 0
            else:
               data = data
       return data    

details['lower'] = details.apply(get_value,list1=li,result_type='expand',axis=1) 

produces this error:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')

I referred the question.Truth value of a series is ambiguous Still I can not rectify the error

One Answer

(Assuming the error comes from the 2nd line)

This question on StackOverflow has a great answer to your problem

Essentially, change

 if ((vars_df['variable_name']) in list1) & (vars_df['direction'] =='up'):

to this

if (((vars_df['variable_name']) in list1) & (vars_df['direction'] =='up')).any():

or to this, if all of the values should be True

if (((vars_df['variable_name']) in list1) & (vars_df['direction'] =='up')).all():

Hope this helps :)

Answered by Toivo Mattila on August 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP