Pandas - 读取.csv文件的结尾

时间:2015-03-01 20:08:27

标签: python pandas

我有一个大的(8 GB)csv gzip文件。我想通过pandas将其读入DataFrame。由于文件的长度很大,我用块读取它并且工作正常,但我知道是否有一种方法只读取最后的x行,而不解压缩整个文件。 非常感谢您的支持。

1 个答案:

答案 0 :(得分:1)

我正在考虑读取数据帧最后几行的各种方法。由于我不确定我是否正确理解您所说的“不解压缩整个文件”的意思,我想知道您是否对以下任何选项感兴趣。


选项 1

使用 pandas.read_csv() 读取 .csv 文件时,可以跳过行,因此它们不包含在导入中。

为此,当调用它时,应该传递 skiprows=[x],其中 x 是要排除的行号(请注意,行编号类似于列表,从 0 开始)。


选项 2

另一个选项可能是将文件转换为 HDF5 并选择开始和停止。举个例子

import pandas as pd 
import numpy as np

df = pd.DataFrame({'Date' : np.random.randn(50000)},index=pd.date_range('20200528',periods=50000,freq='s'))

store = pd.HDFStore('example.h5', mode='w')

store.append('df', df)

rowsnumber = store.get_storer('df').nrows

store.select('df',start=nrows-5,stop=rowsnumber) #Change the start to the number of rows one wants to display starting from the end

选项 3

假设df已经与变量df关联,为了读取最后5行,使用df.iloc

rows = df.iloc[-5:]

df.tail

rows = df.tail(5)