0

I would like to add a '%' symbol to the end of number in a column

df = pd.DataFrame({
    'name': ['A', 'B', 'C'],
    'value': [2.5, 3.6, 4.2]
})

Desired output:

 name| value |
  A  | 2.5 % |
  B  | 3.6 % |
  C  | 4.2 % |

Attempt: (I was thinking on a Regex function or maybe Lambda)

df[["name", "value"]]=df[["value"]].astype(str).replace(r"(\d{2})", r"\1%", regex=True)

  • Use `df['value'].map('{} %'.format)` . Ref link- https://stackoverflow.com/questions/20025882/add-a-string-prefix-to-each-value-in-a-string-column-using-pandas – Divyank Aug 16 '22 at 07:54

1 Answers1

1
df["value_pct"] = df["value"].astype(str) + " %"

The above should give you a dataframe like this:

In [4]: df
Out[4]: 
  name  value value_pct
0    A    2.5     2.5 %
1    B    3.6     3.6 %
2    C    4.2     4.2 %

If you really want to overwrite value, then use this:

df["value"] = df["value"].astype(str) + " %"

That said, are you sure you want to convert the column to string like this? Because then you won't be able to perform any mathematical operations. If you just want to print this out, you shouldn't alter the dataframe. Maybe write a custom print function:

def df_print(df):
    _df = df.copy()
    _df["value_pct"] = df["value"].astype(str) + " %"
    print(_df[["name", "value_pct"]].to_string())
suvayu
  • 4,271
  • 2
  • 29
  • 35