python - 尝试在 Python 中的 Pandas DataFrame 上应用函数
问题描述
我正在尝试应用此函数来填充Age
基于Pclass
和列的Sex
列。但我无法这样做。我怎样才能让它工作?
def fill_age():
Age = train['Age']
Pclass = train['Pclass']
Sex = train['Sex']
if pd.isnull(Age):
if Pclass == 1:
return 34.61
elif (Pclass == 1) and (Sex == 'male'):
return 41.2813
elif (Pclass == 2) and (Sex == 'female'):
return 28.72
elif (Pclass == 2) and (Sex == 'male'):
return 30.74
elif (Pclass == 3) and (Sex == 'female'):
return 21.75
elif (Pclass == 3) and (Sex == 'male'):
return 26.51
else:
pass
else:
return Age
train['Age'] = train['Age'].apply(fill_age(),axis=1)
我收到以下错误:
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
解决方案
您应该考虑使用括号来分隔参数(您已经这样做了)并更改按位运算符的布尔运算符and
以&
避免此类错误。另外,请记住,如果要使用apply
,则应x
为函数使用参数,该参数将成为函数中 lambda 的一部分apply
:
def fill_age(x):
Age = x['Age']
Pclass = x['Pclass']
Sex = x['Sex']
if pd.isnull(Age):
if Pclass == 1:
return 34.61
elif (Pclass == 1) & (Sex == 'male'):
return 41.2813
elif (Pclass == 2) & (Sex == 'female'):
return 28.72
elif (Pclass == 2) & (Sex == 'male'):
return 30.74
elif (Pclass == 3) & (Sex == 'female'):
return 21.75
elif (Pclass == 3) & (Sex == 'male'):
return 26.51
else:
pass
else:
return Age
现在,将 apply 与 lambda 一起使用:
train['Age'] = train['Age'].apply(lambda x: fill_age(x),axis=1)
在示例数据框中:
df = pd.DataFrame({'Age':[1,np.nan,3,np.nan,5,6],
'Pclass':[1,2,3,3,2,1],
'Sex':['male','female','male','female','male','female']})
使用上面提供的答案:
df['Age'] = df.apply(lambda x: fill_age(x),axis=1)
输出:
Age Pclass Sex
0 1.00 1 male
1 28.72 2 female
2 3.00 3 male
3 21.75 3 female
4 5.00 2 male
5 6.00 1 female
推荐阅读
- java - void 方法的 JUnit 测试(输出-输入依赖)
- sql - SQL 修剪非常慢
- batch-file - 检测变量是否包含字符串,然后批量查找该字符串之后的单词
- angular - oidc登录死循环
- python - Python > Selenium + CSV:如何从网站上抓取并将 2 列写入 CSV?
- macos - macOS 核心数据 – toOne 新记录是否在创建时自动分配给 toMany 对象?
- javascript - 如何根据名称(“编号”.js)在文件夹中执行.js文件
- excel - 如何做一个动态的参考?
- javascript - 在 Vue 计算属性中获取 svg 大小
- python - 我在打印时尝试在列表中添加新行,但无法使其正常工作