tiger-sms ChatGPT 账号/ChatGPT 代注册 ChatGPT 账号/ChatGPT 代注册 OpenAI API 代充值

Pandas 读取 csv 文件提示:DtypeWarning: Columns (3) have mixed types. Specify dtype option on import or set low_memory=False.

dajiaka OpenAI API key

在用 Python 处理 csv 文件里,一般都会用到 Pandas 来读取或者存储 csv,之前处理数据也都是这样的,昨天在用 Pandas 处理一个 csv 文件时,出现了一个警告:DtypeWarning: Columns (3) have mixed types. Specify dtype option on import or set low_memory=False.,下面记录下出现这个警告的原因和解决方法。

一、问题描述

在使用 Pandas 的 read_csv 函数时,提示警告:

# 代码
data = pd.read_csv(f)


# 警告
sys:1: DtypeWarning: Columns (3) have mixed types. Specify dtype option on import or set low_memory=False.

从警告的字面意思看是由于第 3 列存在多种数据类型导致的。例如数值 3 被认为了是 int 型,但是数值 3.4 被认为是 str 型。

二、问题解决

按照警告的提示,解决方法有两种:关闭 low_memory 模式或者指定列的数据类型。

1.关闭 low_memory

data = pd.read_csv(f, low_memory=False)

2.指定类型(推荐)

例如我这里把这些列都让 Pandas 看作是 str:

data = pd.read_csv(f, dtype={"site": str, "aqi": str})

三、low_memory 是什么

Pandas 在读取 csv 文件时时按块读取的,并不会一次性读取,并且对于数据的类型“都靠猜”,所以就可能出现了 Pandas 在不同块对同一列的数据“猜”出了不同的数据类型,也就造成了上述的警告。

而如果关闭 low_memory 功能时,Pandas  就会一次性读取 csv 中德所有数据,自然对列的数据类型也只会猜测一次,就不会造成这种警告了。但是关闭 low_memory 时,一旦 csv 文件过大,就会内存溢出,所以建议采取指定类型的方式。

另外,Pandas 官方对于 low_memory 的介绍:

low_memory : boolean, default True
Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the dtype parameter. Note that the entire file is read into a single DataFrame regardless, use the chunksize or iterator parameter to return the data in chunks. (Only valid with C parser)

本文参考:pandas read_csv mixed types问题

赞(10)
关注我们
未经允许不得转载:老王博客 » Pandas 读取 csv 文件提示:DtypeWarning: Columns (3) have mixed types. Specify dtype option on import or set low_memory=False.