Keep % format of float values

前端 未结 3 1905
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题