基于列值的百分比减少

2024-09-30 02:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框如下所示:

question   timeSpent
a          5354
b          2344
c          2555
d          5200
e          3567

我想添加一个额外的列Score,它包含01之间的值。timeSpent(以秒表示)越大,Score越接近0。如果花费的时间较小,则Score接近1

如果timeSpent小于或等于2500,则假设该值为1。然后每经过100秒,它就会下降20%。如果它达到或大于5500,它将保持在0

所以对于2600,分数是0.8,对于2700,分数是0.64,等等

我为每个时间间隔编写if-else语句,但我认为必须有一种更快的方法来完成


Tags: 数据方法间隔if时间语句else分数
1条回答
网友
1楼 · 发布于 2024-09-30 02:29:48

您可以创建一个函数来计算分数,并将其应用于每个timeSpent

def get_score(num):
    if num <= 2500: return 1
    if num >= 5500: return 0
    x = 1
    for _ in range((num - 2500) // 100):
        x *= 0.8
    return x

df = pd.DataFrame({'question': [a, b, c, d, e], 'timeSpent': [5354, 2344, 2555, 5200, 3567]})
df['Score'] = df.timeSpent.apply(lambda x: get_score(x))

输出:

  question  timeSpent     Score
0        a       5354  0.001934
1        b       2344  1.000000
2        c       2555  1.000000
3        d       5200  0.002418
4        e       3567  0.107374

相关问题 更多 >

    热门问题