Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

pandas - Get error the truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I have BirthOfDate column that looks like this

 DateOfBirth
 1980-02-10 
 2005-12-20
 1946-03-03

And I want to add new column, that is age catagorized column . Teen : 13-18, Adult : 19-59, Senior Adult : > 60

I try to make a function, then apply it to new column like this one

def count_age(DateOfBirth):
now = pd.to_datetime('now')
age = (now.year - person['DateOfBirth'].dt.year) - ((now.month - person['DateOfBirth'].dt.month) < 0)

if (age <= 18) & (age >=13):
    return "Teen"
elif (age <= 59) & (age >= 19):
    return "Adult"
elif (age >= 60):
    return "Senior Adult"

person['Age'] = person['DateOfBirth'].apply(count_age)
person

but I get error "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()". Can anyone help me?

Thank you

question from:https://stackoverflow.com/questions/65855758/get-error-the-truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-ite

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your age variable return pandas series not a number. Instead use this

def count_age(person):
  now = pd.to_datetime('now')
  age = (now.year - person['DateOfBirth'].dt.year) - ((now.month - person['DateOfBirth'].dt.month) < 0)
  age_list = age.values
  print(age_list)
  new_list = []
  for age in age_list:
    if (age <= 18) & (age >=13):
        new_list.append("Teen")
    elif (age <= 59) & (age >= 19):
        new_list.append("Adult")
    elif (age >= 60):
        new_list.append("Senior Adult")

  return new_list

person['Age'] = count_age(person)
person

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...