简体   繁体   English

python pandas - 无法将csv字段中的科学记数法转换为字符串?

[英]python pandas - unable to convert scientific notation in a csv field to string?

I'm trying to use pandas to make sure that a csv is outputting certain fields (containing numbers) as strings, not numbers.我正在尝试使用熊猫来确保 csv 将某些字段(包含数字)输出为字符串,而不是数字。

Here's the initial fields in the csv - they are formatted in scientific notation:这是 csv 中的初始字段 - 它们以科学记数法格式设置:

FIPS_BLOCK  FIPS_BLKGR  FIPS_TRACT
5.51E+14    5.51E+11    5.51E+10
5.51E+14    5.51E+11    5.51E+10
5.51E+14    5.51E+11    5.51E+10
5.51E+14    5.51E+11    5.51E+10

How I'm trying to convert to string:我如何尝试转换为字符串:

import pandas as pd

# lst of column names which needs to be string
lst_str_cols = ['FIPS_BLOCK', 'FIPS_BLKGR', 'FIPS_TRACT','FIPS_PLACE']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
df = pd.read_csv(output_files_dir + "//" + output_shp_name + ".csv", dtype=dict_dtypes)
df.to_csv(output_files_dir + "//" + output_shp_name + ".csv")

It's still formatting in scientific notation.它仍然以科学记数法进行格式化。 I've also tried converting to numeric (int64), but it still is outputting in scientific notation, so I'm not sure what else to try.我也试过转换为数字 (int64),但它仍然以科学记数法输出,所以我不知道还能尝试什么。 Thank you.谢谢你。

Thanks.谢谢。

From the pandas documentation you can add the quoting option in the .to_csv method.pandas 文档中,您可以在.to_csv方法中添加引用选项。

For your code对于您的代码

import csv
df.to_csv(output_files_dir + "//" + output_shp_name + ".csv", quoting=csv.QUOTE_NONNUMERIC)

Or if you want to quote everything (including numeric), you could use csv.QUOTE_ALL或者,如果您想引用所有内容(包括数字),您可以使用csv.QUOTE_ALL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM