Keep % format of float values

前端 未结 3 1904
名媛妹妹
名媛妹妹 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})
    
    0 讨论(0)
  • 2021-01-29 02:56

    Maybe using pandas style?

    df.style.format("{:.2%}")
    
    0 讨论(0)
  • 2021-01-29 02:57

    Try this one...

    import math
    import pandas as pd
    
    def get_percentage(value: float):
        """ This function converts the floating-point integer into float
        type percentage string.
        :param value: A floating point integer.
        :return string: Percentage representation of the input value with % symbol at the end.
        """
        if math.isnan(value):
            return "NaN"
        else:
            return "{}%".format(round(value * 100,2))
    
    # Create  a data frame
    data = {'Growth_Rate1': [0.2345,0.1473,math.nan,0.2500],
                'Growth_Rate2': [0.4252,math.nan,0.6936,0.2746],
                'Growth_Rate3': [0.3643,0.1735,0.5925,math.nan],
            }
    df = pd.DataFrame(data)
    
    # Get the shape of the data frame
    rows, cols = df.shape
    
    # Display the data frame
    print(df)
    
    # Display the data frame with formatted values
    print("---"*20)
    print("\t".join(df.columns))
    for row in range(rows):
        for col in range(cols):
            print(get_percentage(df.loc[row][col]), end="\t\t")
        print()
    print("---"*20)
    

    Output:

    ----------------------------------------------------------------------
    
           Growth_Rate1  Growth_Rate2  Growth_Rate3
    0        0.2345        0.4252        0.3643
    1        0.1473           NaN        0.1735
    2           NaN        0.6936        0.5925
    3        0.2500        0.2746           NaN
    ----------------------------------------------------------------------
    
    Growth_Rate1    Growth_Rate2    Growth_Rate3
       23.45%          42.52%          36.43%       
       14.73%             NaN          17.35%       
          NaN          69.36%          59.25%       
       25.00%          27.46%             NaN       
    ----------------------------------------------------------------------
    

    Please let me know whether it worked or not.

    0 讨论(0)
提交回复
热议问题