Keep % format of float values

前端 未结 3 1966
名媛妹妹
名媛妹妹 2021-01-29 02:23

How do you keep your float in the % format?

df[\'growth_rate\'] = df[\'growth_rate\'].replace(\'%\', \'\', regex=True).astype(float, errors=\'ignore         


        
3条回答
  •  野性不改
    2021-01-29 02:41

    You can take your column and send it through to_string:

    output = df.to_string(formatters={'growth_rate': '{:,.2%}'.format})
    print(output)
    
     growth_rate
    0      23.45%
    1      14.73%
    2        nan%
    3      25.00%
    

    This doesn't change your data frame (which is still in float):

    In [ 7]: df
    Out[ 7]: 
       growth_rate
    0       0.2345
    1       0.1473
    2          NaN
    3       0.2500
    

    but generates a string representation of the growth_rate column you can print.

    To output all the columns, pass a list of formatters as long as the number of columns:

    df['growth_rate2'] = [0.1,0.04,0.876,np.nan]
    output = df.to_string(formatters=['{:,.2%}'.format]*2)
    

    To output only particular columns in your special format, use a dictionary with the column names as the keys:

    df['growth_rate3'] = [0.071,0.02,0.,0.66]
    df.to_string(formatters={'growth_rate': '{:,.2%}'.format,
                             'growth_rate3': '{:,.2%}'.format})
    

提交回复
热议问题