【发布时间】:2020-05-01 05:26:52
【问题描述】:
所以我从以下 csv 创建了一个 pandas 数据框:
id age00 education marital gender ethnic industry income00
0 51.965 17 0 1 0 5 76110
1 41.807 12 1 0 0 1 43216
2 36.331 12 1 0 1 3 52118
3 56.758 9 1 1 2 2 47770
我的目标是创建一个名为 future_income 的新列,它获取每一行并使用我的模型计算未来收入。
这是由我在下面创建的一个类中的 predictFinalIncome 变量完成的:
class myModel:
def __init__(self, bias) :
self.bias = bias # bias is a dictionary with info to set bias on the gender function and the ethnic function
def b_gender(self, gender):
effect = 0
if (self.bias["gender"]): # if there is gender bias in this model/world (from the constructor)
effect = -0.0005 if (gender<1) else 0.0005 # This amount to 1.2% difference annually
return self.scale * effect
def b_ethnic(self, ethnic):
effect = 0
if (self.bias["ethnic"]): # if there is ethnic bias in this model/world (from the constructor)
effect = -0.0007 if (ethnic < 1) else -0.0003 if (ethnic < 2) else 0.0005
return self.scale * effect
# other methods/functions
def predictGrowthFactor( self, person ): # edited
factor = 1 + person['education'] + person['marital'] + person['income'] + person['industry']
return factor
def predictIncome( self, person ): # perdict the new income one MONTH later. (At least on average, each month the income grows.)
return person['income']*self.predictGrowthFactor( person )
def predictFinalIncome( self, n, person ):
n_income = self.predictIncome( person )
for i in range(n):
n_income = n_income * i
return n_income
在这种情况下,n 是 120。
简而言之。我想取出每一行,将其放入名为 predictFinalIncome 的类函数中,并在我的 df 上添加一个名为 future_income 的新变量,这是他们 120 个月内的收入。
编辑:
我实际上不需要 person 类。我不小心在确定参数“偏差”的类中删除了我的 init__ 。相反,基于@Cavin Dsouza 的代码。但这不起作用。
然后读取代码如下:
utopModel = myModel( { "gender": False, "ethnic": False } ) # no bias
n =120
#Utopia
u = utopModel
world1['incomeFinal_utop'] = world1.apply(lambda row: u.predictFinalIncome(n, row), axis=1)
所以当它进入 predictFinalIncome 时,错误是这样的:
TypeError: 'str' object cannot be interpreted as an integer
During handling of the above exception, another exception occurred:
KeyError
KeyError: 'income'
【问题讨论】:
-
假设你的数据框是
df,并且你创建了一个myModel类的对象,比如m = myModel(),你不能简单地创建一个列future_income作为-df['future_income'] = df.apply(lambda row: m.predictFinalIncome(n, row), axis=1)?这里,apply函数中的row充当了 Person 对象,因此可能不需要 Person 类。
标签: python pandas numpy class oop