Tanai Goncalves
Tanai Goncalves

Reputation: 69

python - decimal 'dot' to 'comma', use 2 decimals

I have this data, "VALOR" is float:

Periodo VALOR
32021 1096.14
32021 3835.44
32021 2207.90
32021 389.10

I'm trying to change decimal 'dot' to 'comma', and thats fine.

But I need to save the 2 decimals, and when I convert it, it desappear when the last decimal is 0.

df['VALOR'] = np.round(df['VALOR'], decimals=2).astype(str)
df['VALOR'] = df['VALOR'].str.replace('.',',')


df.head()
Periodo VALOR
32021 1096,14
32021 3835,44
32021 2207,9
32021 389,1

How to get the 2 decimals here?

tried this also:

pd.options.display.float_format = '{:,.2f}'.format

and this

df['VALOR'] = df['VALOR'].apply(lambda x: locale.format('%.2f', x))

None of them worked. I need to convert the decimal to comma and maitain the 2 decimals.

Maybe some enconding would resolve? like changing my sys to UTF-8? Already tried to.. but nothing yet.

Regards,

Tanai

Upvotes: 1

Views: 156

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24314

Try with apply() method,replace() method and rstrip() method:

df['VALOR']=df['VALOR'].apply(lambda x: '{:.2f},'.format(x))
df['VALOR'] = df['VALOR'].str.replace('.',',',regex=True)
df['VALOR']=df['VALOR'].str.rstrip(',')

Now If you print df you will get:

    Periodo     VALOR
0   32021       1096,14
1   32021       3835,44
2   32021       2207,90
3   32021       389,10

Upvotes: 2

Related Questions