简体   繁体   中英

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

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 (eg 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.

试试这个(如果你的列中有浮动):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM