pandas replace multiple values one column

后端 未结 6 1747
被撕碎了的回忆
被撕碎了的回忆 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:14

    In [123]: import pandas as pd                                                                                                                                
    
    In [124]: state_df = pd.DataFrame({'state':['Small', 'Medium', 'High', 'Small', 'High']})                                                                    
    
    In [125]: state_df
    Out[125]: 
        state
    0   Small
    1  Medium
    2    High
    3   Small
    4    High
    
    In [126]: replace_values = {'Small' : 1, 'Medium' : 2, 'High' : 3 }                                                                                          
    
    In [127]: state_df = state_df.replace({"state": replace_values})                                                                                             
    
    In [128]: state_df
    Out[128]: 
       state
    0      1
    1      2
    2      3
    3      1
    4      3
    

提交回复
热议问题