【问题标题】:Percentage decrease based on column value基于列值的百分比减少
【发布时间】:2021-09-10 00:06:52
【问题描述】:

我的数据框如下所示:

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 语句,但我认为必须有更快的方法来做到这一点。

【问题讨论】:

    标签: python pandas dataframe percentage


    【解决方案1】:

    您可以创建一个函数来计算分数并将其应用于每个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
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2015-08-13
      • 2021-09-05
      • 1970-01-01
      • 2023-03-31
      • 2019-06-03
      • 1970-01-01
      • 2020-11-23
      • 2013-12-24
      相关资源
      最近更新 更多