如何编写 CSV 文件以便 csv.DictReader() 将其读取为 string/int?

How to write a CSV file so it is read by csv.DictReader() as string/int?

我使用 pandas.DataFrame.to_csv() 将 DataFrame 写入 CSV 文件。在此文件中,其中一列表示 "Year"。问题是,当使用 csv.DictReader() 加载 CSV 文件时,该列显然被读取为浮点数,因此,.0 被添加到它的值中!!以下为准确阅读行:

csvfile = csv.DictReader(of, delimiter="|")

我仔细检查了保存的 CSV 文件,那里根本没有小数点!

如何正确编写 CSV 文件,以便 csv.DictReader() 将某些列作为字符串或至少作为整数读取?

注意:我无法控制 csv.DictReader() 的调用方式。

首先,检查 Year 列的类型:

df['Year'].dtype

如果它是 float64 类型,那么您应该将其转换为整数:

df['Year'] = df['Year'].astype(int)

除非你在该行中有空单元格,否则你需要先填写它们(因为你不能在整数列中有 NaN):

df['Year'].fillna(1234)

或者,为 to_csv() 方法使用参数 float_format