【问题标题】:How to replace (encode) multi values based on value ranges in one column? [duplicate]如何根据一列中的值范围替换(编码)多个值? [复制]
【发布时间】:2021-01-04 06:06:09
【问题描述】:

我想根据其范围更改列中的值,我应该怎么做?

这是一个示例数据集

Id    Number

0      2
1      2
2      2
3      2
4     23
5      6
6     16
7     10
8     15
9      8
10     6
11     9
12     1

Here is the range:

   if number >=6 and <12 then 1
   if number ==12, then 2
   if number >=13 and <=17, then 3
   if number >17 and <=22 then 4
   else 5

我该怎么做?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我会使用 NumPy 的 select():

    import numpy as np
    
    np.select([
        df.Number.between(6, 11),
        df.Number == 12,
        df.Number.between(13, 17),
        df.Number.between(18, 22)],
        [1, 2, 3, 4], 5)
    

    【讨论】:

    • 兹维克非常感谢。我刚跑了。数字没有变化。我会再试一次。谢谢你。如果它不起作用,会通知您
    • @almo:我编写的代码不会修改数据结构,它会生成一个新数组,您需要将其存储在某个地方。附言为什么人们总是在我的名字中留下“n”?
    • @thanks,现在它显示了。有没有办法使用replace、map等?只是想看看是否有其他方法可以解决它。我接受了你的回答:)
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2012-10-13
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多