pandas replace multiple values one column

后端 未结 6 1751
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 07:43

In a column risklevels I want to replace Small with 1, Medium with 5 and High with 15. I tried:

dfm.replace({\'risk\':{\'Small\': \'1\'}},{\'risk\':{\'Medium         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 08:06

    You could define a dict and call map

    In [256]:
    
    df = pd.DataFrame({'a':['Small', 'Medium', 'High']})
    df
    Out[256]:
            a
    0   Small
    1  Medium
    2    High
    
    [3 rows x 1 columns]
    In [258]:
    
    vals_to_replace = {'Small':'1', 'Medium':'5', 'High':'15'}
    df['a'] = df['a'].map(vals_to_replace)
    df
    Out[258]:
        a
    0   1
    1   5
    2  15
    
    [3 rows x 1 columns]
    
    
    In [279]:
    
    val1 = [1,5,15]
    df['risk'].update(pd.Series(val1))
    df
    Out[279]:
      risk
    0    1
    1    5
    2   15
    
    [3 rows x 1 columns]
    

提交回复
热议问题