pandas to_csv:在将candv写入csv时,禁止csv文件中的科学记数法 [英] pandas to_csv: suppress scientific notation in csv file when writing pandas to csv

查看:8548
本文介绍了pandas to_csv:在将candv写入csv时,禁止csv文件中的科学记数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个熊猫df到csv。当我将它写入csv文件时,其中一列中的某些元素被错误地转换为科学记数法/数字。例如,col_1有字符串,如104D59。字符串在csv文件中通常表示为字符串,因为它们应该是。然而,偶尔的字符串,例如'104E59'正被转换成科学记数法(例如,1.04E61),并且在随后的csv文件中被表示为整数。

I am writing a pandas df to a csv. When I write it to a csv file, some of the elements in one of the columns are being incorrectly converted to scientific notation/numbers. For example, col_1 has strings such as '104D59' in it. The strings are mostly represented as strings in the csv file, as they should be. However, occasional strings, such as '104E59', are being converted into scientific notation (e.g., 1.04 E 61) and represented as integers in the ensuing csv file.

我想CSV文件导出到一个软件包(即熊猫 - > CSV - > software_new)而这种变化在数据类型导致与出口问题。

I am trying to export the csv file into a software package (i.e., pandas -> csv -> software_new) and this change in data type is causing problems with that export.

有一种方法可以将df写入csv,确保df ['problem_col']中的所有元素在生成的csv中表示为字符串,科学计数法?

Is there a way to write the df to a csv, ensuring that all elements in df['problem_col'] are represented as string in the resulting csv or not converted to scientific notation?

下面是我用熊猫写DF到CSV代码:
df.to_csv('df.csv',编码='UTF- 8')

Here is the code I have used to write the pandas df to a csv: df.to_csv('df.csv', encoding='utf-8')

我还检查问题列的dtype:
df.dtype,df ['problem_column']是一个对象

I also check the dtype of the problem column: for df.dtype, df['problem_column'] is an object

推荐答案

使用 float_format 参数:

In [11]: df = pd.DataFrame(np.random.randn(3, 3) * 10 ** 12)

In [12]: df
Out[12]:
              0             1             2
0  1.757189e+12 -1.083016e+12  5.812695e+11
1  7.889034e+11  5.984651e+11  2.138096e+11
2 -8.291878e+11  1.034696e+12  8.640301e+08

In [13]: print(df.to_string(float_format='{:f}'.format))
                     0                     1                   2
0 1757188536437.788086 -1083016404775.687134 581269533538.170288
1  788903446803.216797   598465111695.240601 213809584103.112457
2 -829187757358.493286  1034695767987.889160    864030095.691202

其对于to_csv类似:

Which works similarly for to_csv:

df.to_csv('df.csv', float_format='{:f}'.format, encoding='utf-8')

这篇关于pandas to_csv:在将candv写入csv时,禁止csv文件中的科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆