得到一个系列的真值不明确的错误。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
Get error the truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
我的 BirthOfDate 列看起来像这样
DateOfBirth
1980-02-10
2005-12-20
1946-03-03
我想添加新的列,即年龄分类列。青少年:13-18 岁,成人:19-59 岁,老年:> 60
我试着做一个函数,然后将它应用到像这样的新列中
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
但我收到错误“系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或a.all()”。谁能帮帮我?
谢谢
您的年龄变量 return pandas 系列不是数字。而是使用这个
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
以下应该有效,
age = (now.year - DateOfBirth.year) - ((now.month - DateOfBirth.month) < 0)
我的 BirthOfDate 列看起来像这样
DateOfBirth
1980-02-10
2005-12-20
1946-03-03
我想添加新的列,即年龄分类列。青少年:13-18 岁,成人:19-59 岁,老年:> 60
我试着做一个函数,然后将它应用到像这样的新列中
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
但我收到错误“系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或a.all()”。谁能帮帮我?
谢谢
您的年龄变量 return pandas 系列不是数字。而是使用这个
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
以下应该有效,
age = (now.year - DateOfBirth.year) - ((now.month - DateOfBirth.month) < 0)