简体   繁体   English

如何在 CSV 文件 Python 中将整数存储为字符串

[英]How to store integers as strings in CSV file Python

When trying to save some number as a string type in CSV file, then saving this file and reading it again, the file shows this saved data as a numpy.int64 instead of a string.当试图在 CSV 文件中将一些数字保存为字符串类型,然后保存此文件并再次读取时,该文件将此保存的数据显示为numpy.int64而不是字符串。 How can this be solved so when reading the csv file it reads it as a string, not int?如何解决这个问题,以便在读取 csv 文件时将其读取为字符串,而不是 int?

Here is a Python script that describes this case这是描述这种情况的 Python 脚本

import pandas as pd

df = pd.DataFrame(columns=['ID'])

ID = '1'
df = df.append(pd.DataFrame([[ID]], columns=['ID']))
df.to_csv('test.csv', index=False)

"""
now the csv file looks like this:

ID
1
"""

df = pd.read_csv('test.csv')
print(df['ID'].iloc[0] == ID)  # this will print False
print(type(df['ID'].iloc[0]))  # this will print <class 'numpy.int64'>

The CSV file format doesn't distinguish between different data types. CSV 文件格式不区分不同的数据类型。 You have to specify the data type when reading the CSV with pandas.用pandas读取CSV时必须指定数据类型。

df = pd.read_csv("test.csv", dtype=str)

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

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