Search code examples
pythonpandasdataframeroundingdecimal-point

How to convert (number with % sign) to (round(number) with % sign)


df is as follows

    col1        col2
    10.56%      a
    55.78%      b
    700%        c
    118.13%     d
    200%        e
    102%        f
    45.25%      g
    67.765%     h

i want df['col1'] like below(rounded off to 0 decimal with '%' sign):

col1
11%
56%
700%
118%
200%
102%
45%
68%

My code is not working properly for some entries

df['col1'] = [re.sub("%","",str(x)) for x in list(df['col1'])]
df['col1'] = df['col1'].map(lambda x: pd.to_numeric(x, errors='ignore'))
df = df.round({'col1': 0})
df['col1'] = [re.sub(".0","%",str(x)) for x in list(df['col1'])]

Like 700% changes to 7%

118.13 to %%

some to %6%

and for some entries it is working fine.

Please help me with this!!!


Solution

  • Quick and dirty way:

    import pandas as pd
    
    perc_df = pd.DataFrame(
        {'col1' : ['65.94%', '761.19%', '17281.0191%', '9.4%', '14%'],
         'col2' : ['a', 'b', 'c', 'd', 'e']
    })
    
    
    perc_df['col1'] = pd.to_numeric(perc_df['col1'].str.replace('%', ''))
    perc_df['col1'] = pd.Series([round(val, 2) for val in perc_df['col1']], index = perc_df.index)
    perc_df['col1'] = pd.Series(["{0:.0f}%".format(val) for val in perc_df['col1']], index = perc_df.index)