[英]Applying function across column for each row to create new variable in a dataframe
我有一个实验的“数据框”,通过询问例如choice3 来估计参与者的折扣率:他们更愿意现在拿100 美元还是1 个月后拿105 美元? 选择 4:他们更愿意现在拿 100 美元还是 1 个月后拿 120 美元。
下面是一个例子,索引是参与者 id,choice1 到choice4,作为延迟奖励 1 个月提出的增加补偿金额:
指数 | 选择1 | 选择2 | 选择3 | 选择4 |
---|---|---|---|---|
0 | 100 | 100 | 100 | 100 |
1 | 100 | 102 | 105 | 120 |
2 | 100 | 100 | 100 | 120 |
3 | 100 | 100 | 100 | 100 |
4 | 100 | 100 | 105 | 120 |
我正在尝试创建一个新列“折扣”,该列采用参与者第一次偏离选择 100 美元时的百分比变化,例如参与者 1 为 0.02,参与者 2 为 0.2,等等。
我试图应用 function 来创建一个新变量作为列:
def dis_cal(row):
dis = 0
col_index = 0
rate = (lambda now, later: (later - now)//now)
while dis == 0 and col_index < 3:
dis = rate(float(row[col_index]), float(row[col_index + 1]))
col_index += 1
def discount(df):
df.loc[:,"discount"] = df.apply(lambda row: dis_cal(row), axis = 1)
但是 while 循环中的dis都等于 0.0,在新列discount中显示为None
这是我的第一个数据分析项目,我真的需要一些帮助。 非常感谢!
对于参与者 0,while 循环不会终止。 所以你必须在 col_index 上添加一个约束。
while dis == 0 and col_index<3
这应该有效。 还有一件事,我们必须从 function 返回“率”。
col_index += col_index + 1
这应该替换为
col_index = col_index + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.