【发布时间】:2019-01-20 05:57:25
【问题描述】:
我在 pandas 数据框中有一些数据,存储如下:
0 纳斯达克 AAPL 1.63 3.51 2.20
1 纳斯达克 AAPL 2.40 3.59 1.74
当我将它导出到 CSV 文件或 SQLite 数据库时,任何第二个小数位为零的数字都会被截断到小数点后一位(例如 2.40 变为 2.4)。
我用于导出的代码是:
""" Export data to CSV file """
# Output final data as CSV
df.to_csv('stock_data-US.csv', sep=',', float_format='%.2f', encoding='utf-8', index=True)
# Connect to the database file
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
""" Export dataframe to sqlite table """
# Export pandas array to sqlite table
df.to_sql("stock_data_US", conn, if_exists='replace', index=False)
# Commit changes
conn.commit()
# Close database connection
conn.close()
如您所见,我指定了浮点格式,但这似乎被忽略了(因为小数位被四舍五入)。理想情况下,我希望所有导出的数字在小数点后两位保持一致。
提前感谢您的支持!
【问题讨论】:
-
您可能应该使用不同的示例,例如 2.40 == 2.4! 1.74 是否截断为 1.7?
-
不,1.74 保持为 1.74。 2.20 截断为 2.2,这是我不想要的。如果我无法修复导出,我在想什么,当我将 csv 导入 Pandas 时,我可以恢复零吗?
-
为什么丢弃的零很重要?是出于审美原因吗?