【问题标题】:How to specify the data type and format when exporting to csv using Pandas?使用 Pandas 导出到 csv 时如何指定数据类型和格式?
【发布时间】:2016-07-20 14:06:47
【问题描述】:

我有一个 pandas 数据框,目前所有列都是浮点数,我正在使用 DF.to_csv 将其导出到 csv 文件。

我希望将其中一列导出为 int 而不是 float。第二列有很多小数的数字,并以科学计数法格式导出。我想导出为具有一定精度的常规十进制数,而不是科学计数法。

假设我的 DF 被称为 DataOut 并且有列 'A'、'B' 和 'C'

有什么可以补充的吗

DataOut.to_csv(filename, mode = 'w', header = False , index=False)

这样A中的值导出为int,B中的值导出为小数,最大精度为20位?

【问题讨论】:

  • 为什么不直接复制 DataOut 并进行所需的更改,然后在该副本上调用 .to_csv()

标签: python pandas


【解决方案1】:

复制您的数据框,将各个列四舍五入为整数,然后导出 CSV:

import pandas as pd
import random
#generate a dataframe with two columns, both floating point
df = pd.DataFrame({'A':[random.random()*10 for i in range(10)],
                 'B':[random.random()*20 for i in range(10)]})
df2 = df.copy() #make a copy to preserve your original
df2.loc[:, 'A'] = df2['A'].apply(int) #convert A to an int
df2.loc[:, 'B'] = df2['B'].round(20) #round B to 20 points of precision
df2.to_csv('test.csv', header = None, index = False)

【讨论】:

    【解决方案2】:

    对于浮动

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

    来源https://stackoverflow.com/a/23006399/4941927 大概用float_format也可以转成int,但我不知道。

    对于 int 转换,我认为可以在将解析器转换为纯文件之前使用 round() 函数和生成器,但我敢肯定,因为我从不使用 panda

    http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html

    我会看到你的完整代码@AlexKinman

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      • 2017-05-25
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多