【问题标题】:How to edit columns values based on another value?如何根据另一个值编辑列值?
【发布时间】:2021-12-16 00:17:49
【问题描述】:

我的数据名是这样的:

val    type
10     new
70     new
61     new
45     old
32     new
77     mid
11     mid

对于“类型”列中的值,如果值是新的,我想根据 val 列对其进行编辑。如果 val 中的 value = 20 且 = 50,则必须为 new-3。所以想要的结果是:

val    type
10     new-1
70     new-3
61     new-3
45     old
32     new-2
77     mid
11     mid

怎么做?

【问题讨论】:

    标签: python python-3.x dataframe if-statement


    【解决方案1】:

    我会使用pd.cut:

    >>> df['type'] = df['type'].where(df['type'].ne('new'), df['type'] + '-' + pd.cut(df['val'], [0, 20, 50, float('inf')], labels=[1, 2, 3]).astype(str))
    >>> df
       val   type
    0   10  new-1
    1   70  new-3
    2   61  new-3
    3   45    old
    4   32  new-2
    5   77    mid
    6   11    mid
    >>> 
    

    【讨论】:

    • 我稍微编辑了我的问题,但它是错误的。必须是If value in val is =< 20, it must be new-1, if > 20 and < 50, it must be new-2,if >= 50, it must be new-3
    • @skulldoger 是的,然后将20 设为2150 应该是 49 我猜
    • @skulldoger 用工作代码编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2023-02-23
    • 2019-11-02
    • 2018-12-04
    • 2018-04-22
    • 1970-01-01
    相关资源
    最近更新 更多