微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 高效地将最后’n’行CSV读入DataFrame

一些方法可以做到这一点:

>阅读整个CSV,然后使用df.tail
>以某种方式反转文件(对于大文件最好的方法是什么?)然后使用nrows参数来读取
>以某种方式查找CSV中的行数,然后使用skiprows并读取所需的行数.
>也许做块读取丢弃初始块(虽然不知道这将如何工作)

可以用更简单的方式完成吗?如果不是,应该优先考虑这三者中的哪一个?为什么?

可能相关:

> Efficiently finding the last line in a text file
> Reading parts of ~13000 row CSV file with pandas read_csv and nrows

没有直接关系:

> How to get the last n row of pandas dataframe?

解决方法:

我不认为熊猫在read_csv提供了这样做的方法.

也许最好的(一次通过)是使用collections.deque

from collections import deque
from StringIO import StringIO

with open(fname, 'r') as f:
    q = deque(f, 2)  # replace 2 with n (lines read at the end)

In [12]: q
Out[12]: deque(['7,8,9\n', '10,11,12'], maxlen=2)
         # these are the last two lines of my csv

In [13]: pd.read_csv(StringIO(''.join(q)), header=None)

值得尝试的另一个选择是get the number of lines in a first pass,然后再次读取文件,使用read_csv跳过该行数(减去n)…

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐