python - 读取 csv 文件时的混合类型。原因、修复和后果

标签 python csv pandas

当 Pandas 发出这个警告时到底发生了什么?我应该担心吗?

In [1]: read_csv(path_to_my_file)
/Users/josh/anaconda/envs/py3k/lib/python3.3/site-packages/pandas/io/parsers.py:1139: 
DtypeWarning: Columns (4,13,29,51,56,57,58,63,87,96) have mixed types. Specify dtype option on import or set low_memory=False.              

  data = self._reader.read(nrows)

我假设这意味着 Pandas 无法从这些列的值中推断出类型。但如果是这样的话,Pandas 最终会为这些列使用什么类型

此外,类型总是可以在事后恢复吗? (收到警告后),或者是否存在无法正确恢复原始信息的情况,我应该预先指定类型?

最后,low_memory=False 究竟是如何解决这个问题的?

最佳答案

重新访问 mbatchkarov 的链接,low_memorynot deprecated . 是now documented :

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)

I have asked resulting in mixed type inference 是什么意思,chris-b1 回答:

It is deterministic - types are consistently inferred based on what's in the data. That said, the internal chunksize is not a fixed number of rows, but instead bytes, so whether you can a mixed dtype warning or not can feel a bit random.

那么,Pandas 最终为这些列使用了什么类型?

下面的独立示例回答了这个问题:

df=pd.read_csv(StringIO('\n'.join([str(x) for x in range(1000000)] + ['a string'])))
DtypeWarning: Columns (0) have mixed types. Specify dtype option on import or set low_memory=False.

type(df.loc[524287,'0'])
Out[50]: int

type(df.loc[524288,'0'])
Out[51]: str

csv数据的第一部分看到只有int,所以转为int, 第二部分也有一个字符串,因此所有条目都保留为字符串。

事后总能恢复类型吗? (收到警告后)?

我想重新导出到 csv 并使用 low_memory=False 重新读取应该可以完成这项工作。

low_memory=False 究竟是如何解决这个问题的?

它在决定类型之前读取所有文件,因此需要更多内存。

关于python - 读取 csv 文件时的混合类型。原因、修复和后果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25488675/

相关文章:

python - 根据每个组的频率添加一列

python - 写入行数超过 45 个字节的二进制文件 : binascii. 错误:一次最多 45 个字节

python - 如何遍历列表中的每个字符串?

python - 创建 numpy 转换矩阵数组的正确方法是什么

Python MySQL CSV导出为json奇怪编码

linux - 如何在 unix 中更改 .csv 文件中的日期格式

python - 使用 pandas matplotlib 在 x 轴上显示文本描述而不是数字

csv - 未知列的 read_csv 转换器

python - 如何获取 matplotlib 中轴上单个单位的长度(以像素为单位)?

python - Pandas read_excel() 导入 xlrd 失败