python - 尝试在 pandas DataFrame 上应用函数来计算分数?
问题描述
我创建了如下给出的用户定义函数并尝试应用于 DataFrame,但出现错误:-“TypeError: ("scoreq() missing 3 required positional arguments: 'ADVTG_TRGT_INC', 'AGECD', and 'PPXPRI'", 'occurred在索引 ADVNTG_MARITAL_STAT')"
def scoreq(PCT_NO_OPEN_TRDLN, ADVTG_TRGT_INC, AGECD, PPXPRI):
scoreq += -0.3657
scoreq += (ADVNTG_MARITAL_STAT in ('2'))*-0.039
scoreq += (ADVTG_TRGT_INC in ('7','6','5','4'))*0.1311
scoreq += (AGECD in ('7','2'))*-0.1254
scoreq += (PPXPRI in (-1))*-0.1786
return scoreq
df_3Var['scoreq'] = df_3Var.apply(scoreq)
"TypeError: ("scoreq() missing 3 required positional arguments: 'ADVTG_TRGT_INC', 'AGECD', and 'PPXPRI'", 'occurred at index ADVNTG_MARITAL_STAT')"
df_3Var:-
ADVNTG_MARITAL_STAT ADVTG_TRGT_INC AGECD PPXPRI
0 1 5 6 -1
1 2 6 5 -1
2 1 2 2 -1
3 2 7 6 133
4 2 1 3 75
解决方案
您在函数中使用了列名作为参数scoreq
,但这不是它的工作方式。它应该接收常规参数。
您有两个选择:将整行发送到scoreq
,或仅发送相关值:
def scoreq(row):
scoreq = row["...."]
...
return scoreq
df_3Var['scoreq'] = df_3Var.apply(scoreq)
或直接仅发送值:
df_3Var['scoreq'] = df_3Var.apply(lambda row: scoreq(row["..."], row["..."]))
此外,您可能希望将scoreq
函数内部的数字作为数字而不是字符串处理:例如scoreq += (row["PPXPRI"]==(-1))*-0.1786
,而不是in
。
推荐阅读
- kotlin - 如何做 livedata.postValue(any()) 的 coVerifyOrder - 它返回 io.mockk.MockKException:匹配模拟签名失败
- r - GGPlot2 中带有子组的森林图
- php - Ajax $_POST 发送到 php 时未设置
- c - 在C中,关闭程序后再次打开该程序然后如何存储该初始值
- amazon-web-services - 没有端口号,域无法工作
- java - 数组长度不同?
- ios - NSNotificationCenter 可以在不同框架之间进行通信吗?
- cmake - 不要展开 CMake 列表变量
- javascript - react-pose 延迟姿势组高度转换,直到孩子之后
- ios - 与 ios 中的 .overFullScreen 演示样式相比,使用 .fullScreen 演示样式的好处