首页 > 解决方案 > 带有额外零的熊猫 to_csv

问题描述

我在将 csv 读取到数据帧时遇到了一些问题,然后当我转换为 csv 时,它会包含额外的小数。

目前使用 pandas 1.0.5 和 python 3.7

例如,考虑下面的简单示例:

from io import StringIO
import pandas as pd


d = """ticker,open,close
aapl,108.922,108.583
aapl,109.471,110.25
aapl,113.943,114.752
aapl,117.747,118.825
"""


df = pd.read_csv(StringIO(d), sep=",", header=0, index_col=0)
print(df)
print("\n", df.to_csv())

输出是:

           open    close
ticker                  
aapl    108.922  108.583
aapl    109.471  110.250
aapl    113.943  114.752
aapl    117.747  118.825

ticker,open,close
aapl,108.92200000000001,108.583
aapl,109.471,110.25
aapl,113.943,114.75200000000001
aapl,117.74700000000001,118.825

如您所见,to_csv()输出中添加了额外的零。如果我将 read_csv 更改为 dtype=str ,df = pd.read_csv(StringIO(d), sep=",", dtype=str, header=0, index_col=0)那么我将获得所需的输出,但我希望 dtype 由 pandas 决定,为 int64 或根据列值浮动。而不是强迫所有人成为对象/字符串。

有没有办法在不强制 dtype 为 str 的情况下消除这些额外的零?

标签: pythonpandas

解决方案


您可以使用浮点格式参数:

d = """ticker,open,close
aapl,108.922,108.583
aapl,109.471,110.25
aapl,113.943,114.752
aapl,117.747,118.825
"""

df = pd.read_csv(StringIO(d), sep=",", header=0, index_col=0)
df.to_csv('output.csv',float_format='%.3f')

#This is how the output.csv file looks:

ticker,open,close
aapl,108.922,108.583
aapl,109.471,110.250
aapl,113.943,114.752
aapl,117.747,118.825

推荐阅读