You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas to_csv导出CSV时如何去除整数后的.0?

Fixing Integer-to-Decimal Conversion in Pandas to_csv Exports

I totally get this frustration—nothing’s more annoying than seeing clean integers turn into 1520.0 in your CSV output, especially when you’ve got tons of columns to handle. Let’s walk through a few simple, scalable solutions to fix this without manually tweaking every column:

1. Quick global fix with float_format (for all float-as-integer columns)

If every float column in your DataFrame is actually an integer (no real decimal values needed), use the float_format parameter in to_csv to force all floats to export as whole numbers:

todo.to_csv('D:\prueba.csv', sep=',', header=False, index=False, float_format='%.0f')

This tells Pandas to format all float values with zero decimal places, so 1520.0 becomes 1520 in the output. Just note: this affects every float column, so skip this if you have columns that need to keep decimals.

2. Target specific columns with formatters (for mixed column types)

If only certain columns need the integer treatment, use the formatters parameter. For large numbers of columns, you can even generate the formatter dictionary dynamically:

Explicit column selection:

# List columns that should be integers
int_columns = ['user_id', 'order_number', 'product_count']
formatter_dict = {col: '{:.0f}'.format for col in int_columns}

todo.to_csv('D:\prueba.csv', sep=',', header=False, index=False, formatters=formatter_dict)

Auto-detect whole-number float columns:

If you want to automatically pick float columns that only contain whole numbers:

# Identify float columns where all values are whole numbers
whole_num_float_cols = [
    col for col in todo.select_dtypes(include='float').columns 
    if (todo[col] % 1 == 0).all()
]

formatter_dict = {col: '{:.0f}'.format for col in whole_num_float_cols}

todo.to_csv('D:\prueba.csv', sep=',', header=False, index=False, formatters=formatter_dict)

3. Cleanest long-term fix: Use nullable integer types

If your columns have missing values (NaN) that forced them to be float type in the first place, switch to Pandas’ nullable integer type (Int64 with a capital I) to preserve integer formatting while supporting NaN:

# Convert columns to the most appropriate data types (including nullable integers)
todo = todo.convert_dtypes()

# Export without extra formatting—integers stay as integers!
todo.to_csv('D:\prueba.csv', sep=',', header=False, index=False)

The convert_dtypes() method automatically adjusts columns to their optimal type, so your CSV will output 1520 instead of 1520.0 even if there were missing values in the column.


内容的提问来源于stack exchange,提问作者Elvis Velasque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:57:02