如何使用pd.read_csv()对文件进行迭代分块,以及
保留数据类型和其他元信息,就好像我阅读了整个
数据集?
我需要读取的数据集太大,无法放入内存中。我想使用pd.read_csv导入文件,然后立即将块附加到hdfstore中。然而,数据类型推断对随后的块一无所知。
如果存储在表中的第一个块只包含int,而后续块包含float,则将引发异常。因此,我需要首先使用read_csv迭代数据帧,并保留最高的推断类型。此外,对于对象类型,我需要保留最大长度,因为这些长度将作为字符串存储在表中。
有没有一种泛泛的方法可以只保留这些信息而不读取整个数据集?

最佳答案

我不认为这是直觉,否则我就不会发布这个问题了。但熊猫再一次让事情变得轻而易举。但是,保留这个问题,因为这些信息可能对处理大数据的其他人有用:

In [1]: chunker = pd.read_csv('DATASET.csv', chunksize=500, header=0)

# Store the dtypes of each chunk into a list and convert it to a dataframe:

In [2]: dtypes = pd.DataFrame([chunk.dtypes for chunk in chunker])

In [3]: dtypes.values[:5]
Out[3]:
array([[int64, int64, int64, object, int64, int64, int64, int64],
       [int64, int64, int64, int64, int64, int64, int64, int64],
       [int64, int64, int64, int64, int64, int64, int64, int64],
       [int64, int64, int64, int64, int64, int64, int64, int64],
       [int64, int64, int64, int64, int64, int64, int64, int64]], dtype=object)

# Very cool that I can take the max of these data types and it will preserve the hierarchy:

In [4]: dtypes.max().values
Out[4]: array([int64, int64, int64, object, int64, int64, int64, int64], dtype=object)

# I can now store the above into a dictionary:

types = dtypes.max().to_dict()

# And pass it into pd.read_csv fo the second run:

chunker = pd.read_csv('tree_prop_dset.csv', dtype=types, chunksize=500)

10-04 11:48
查看更多