How to format float columns of dataframe to desired decimal places while writing into delimited file?

Question:

So my dataframe has a bunch of columns for pricings which hold values like 16.99 for 16 dollars and 99 cents. I want my pricing to be correct till cents. But while exporting it to csv, it truncates pricing by removing last zero in cases where cents are multiples of 10 (e.g. 16.50 turns into 16.5). Formatting it or even formatting and then parsing it as string does not help:

for col in df.columns:
    if col.__contains__('USD'):
        df[col] = '$'+df[col].round(decimals=2).astype(str).str.strip()
df.to_csv('pricing.txt', 't')

No matter how any decimals I pass there as arguments it does not work. Current workaround is to write a separate function with conditional formatting but is there a way to do it via pandas itself.

Asked By: Hamza

||

Answers:

Try this (if you have float in in your column):

df[col] = df[col].map('${:,.2f}'.format)
Answered By: O Pardal

this solution produces WARNING

Answered By: JAGJ jdfoxito
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.