gpt4 book ai didi

python - 高效地将 CSV 的最后 'n' 行读入 DataFrame

转载 作者:太空狗 更新时间:2023-10-29 17:53:15 25 4
gpt4 key购买 nike

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

  1. 读取整个 CSV,然后使用 df.tail
  2. 以某种方式反转文件(对大文件执行此操作的最佳方法是什么?)然后使用 nrows 参数读取
  3. 以某种方式找到 CSV 中的行数,然后使用 skiprows 并读取所需的行数。
  4. 也许进行 block 读取并丢弃初始 block (尽管不确定这将如何工作)

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

可能相关:

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

不直接相关:

  1. How to get the last n row of pandas dataframe?

最佳答案

我认为 pandas 在 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)

关于python - 高效地将 CSV 的最后 'n' 行读入 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17108250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com