python - 带有额外零的熊猫 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 的情况下消除这些额外的零?
解决方案
您可以使用浮点格式参数:
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
推荐阅读
- c# - 在运行时为属性设置一个值
- c# - Microsoft Graph 搜索文件结果缺少 parentReference 中的路径属性
- python - 在位置参数和选项之间共享 dest
- ansible - Ansible:从列表中删除空值并将其分配给新列表
- azure-devops - Azure DevOps 自托管 Windows 构建代理失败 git 远程克隆 (128)
- react-native - 如何修复此错误:java.lang.Double 无法在 react-native 中转换为 java.lang.String?
- windows - 跨平台检查正在使用的端口
- generics - 如何提供泛型函数作为类型参数?
- azure-devops - 在发布管道的第一阶段更改所有 Web.*.config 文件
- mysql - 使用 MYSQL 提取嵌套 JSON 对象中的数组