Search code examples
pythonpython-3.xpandasdataframenumber-formatting

How can I add comma into existing value in DataFrame?


I scraped a DataFrame from one website but during scraping I lost comma in values, so it looks like below:

name   price 
x       100
y       89
z       123584

Now I have to modify values in column "price" by adding comma in each value on the second place counting by right. The result should be like this:

name   price 
x       1,00
y       0,89
z       1235,84

Do you have any ideas how I can achieve this?


Solution

  • We can try using str.replace here:

    df['price'] = df['price'].astype('str').str.replace(r'^(\d{2})$', '0\\1')
                                           .str.replace(r'^(\d+)(\d{2})$', '\\1,\\2')
    

    The first call to str.replace prepends a leading zero for those prices consisting of only two (decimal) numbers. The second call inserts a comma separator before the final two decimal digits.