【问题标题】:How map numerical values in pandas dataframe into a discrete set?如何将 pandas 数据框中的数值映射到离散集?
【发布时间】:2022-11-02 20:03:48
【问题描述】:

我有一个数据框,其列 distances 的整数值介于 1 到 3500 之间。我想根据 distance 值为每个样本分配 (0.25, 0.5, 1, 2) 中的权重。

| Distances            | weights |
| ---------            | ------- |
| >= 3000              | 0.25    |
| >= 2000 and < 3000   | 0.5     |
| >= 1000 and < 2000   | 1       |
| < 1000               | 2       |

对于如下数据框,

sample distances
First 3234
Second 465
Third 1200

权重应该是{0.25, 2, 1}。有什么好方法可以做到这一点?

【问题讨论】:

标签: python pandas


【解决方案1】:

考虑到数据框被称为df,可以使用列表推导来做到这一点,如下所示

df['weights'] = [0.25 if x >= 3000 else 0.5 if x >= 2000 and x < 3000 else 1 if x >= 1000 and x < 2000 else 2 for x in df['distances']]

[Out]:

   sample  distances  weights
0   First       3234     0.25
1  Second        465     2.00
2   Third       1200     1.00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 2018-10-10
    • 2018-08-29
    • 1970-01-01
    • 2021-08-21
    • 2015-07-24
    相关资源
    最近更新 更多