【问题标题】:Python3: How to keep the leading zero when exporting a dataframe to a csv or text filePython3:将数据框导出到 csv 或文本文件时如何保持前导零
【发布时间】:2019-10-15 18:21:36
【问题描述】:

我正在使用以下命令:(python3)

Mydataframe__df.to_csv(string_io, sep=',', quoting=csv.QUOTE_ALL, header=True, index=False , encoding='utf-8')
df_writer = Mydata_Output.get_writer('/MYFILE_TEST.csv')
df_string = string_io.getvalue()

# save the string as bytes to with the writer
df_writer.write(df_string.encode('utf-8'))

# close the writer connection
df_writer.close()

问题在于格式为“012345”的列,即使使用记事本打开输出文件,即使列格式在数据框中设置为字符串,输出文件中的前导 0 也会被删除。

【问题讨论】:

    标签: python-3.x formatting export-to-csv


    【解决方案1】:

    我也是新来的,所以这里没有街头信誉可以发表评论。

    您可以通过在输出数据之前转换为字符串来保留前导零。例如,假设您希望数据列中有八位数字,您可以使用 zfill 将字符串左填充零,使其长度为八位。

    outvar = str(numvar).zfill(8)
    

    【讨论】:

    • 我会试试的。我想我必须为每一列定义一个格式。感谢您的回答。
    • 我刚刚发现了 zfill!我更新了我的答案。如果这解决了您的问题并且您可以接受它作为答案,我们将不胜感激。
    • 现在很好,谢谢 - 我的文件并不总是具有相同的长度,但我找到了解决方案。我会在这里发布。
    【解决方案2】:

    前导 0 的问题是,当我们在写入 csv 之前将数据帧加载到 panda 中时,默认情况下 panda 会推断其自己的数据类型。 .get_dataframe(infer_with_pandas=False) 强制保留源数据帧。 问题变成当我们在数据中有空值(字符串数据字段除外)时,熊猫不喜欢它,所以我们需要将所有内容更改为字符串或在...之前清理数据。 在此处的一份出版物中找到了 .get_dataframe(infer_with_pandas=False) 。我稍后会尝试引用它。

    # Read recipe inputs
    Mydataframe = dataiku.Dataset("TESTING_for_leading0")
    Mydataframe_df = Mydataframe.get_dataframe(infer_with_pandas=False)
    
    Mydataframe_df.to_csv(string_io, sep=',', quoting=csv.QUOTE_ALL, header=True, index=False , encoding='utf-8')
    df_writer = Mydata_Output.get_writer('/MYFILE_TEST.csv')
    df_string = string_io.getvalue()
    
    # save the string as bytes to with the writer
    df_writer.write(df_string.encode('utf-8'))
    
    # close the writer connection
    df_writer.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2019-10-25
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多