【问题标题】:Way to read first few lines for pandas dataframe读取熊猫数据框前几行的方法
【发布时间】:2013-02-07 04:09:15
【问题描述】:

有没有一种内置方法可以使用read_csv 来只读取文件的前n 行而不提前知道行的长度?我有一个需要很长时间才能读取的大文件,并且偶尔只想使用第一行,比如 20 行来获取它的样本(并且不想加载完整的东西并占据它的头部)。

如果我知道总行数,我可以执行footer_lines = total_lines - n 之类的操作并将其传递给skipfooter 关键字arg。我目前的解决方案是使用 python 和 StringIO 手动抓取第一行 n 到 pandas:

import pandas as pd
from StringIO import StringIO

n = 20
with open('big_file.csv', 'r') as f:
    head = ''.join(f.readlines(n))

df = pd.read_csv(StringIO(head))

这还不错,但是有没有更简洁的“pandasic”(?)方法来使用关键字或其他东西?

【问题讨论】:

  • 查看如何加载最后 N 行 checkout this SO post
  • 您的意思是“pandastic”吗? :)

标签: python pandas csv dataframe


【解决方案1】:

我会在 read_csv 中使用“skiprows”参数,例如:

df = pd.read_csv(filename, skiprows=range(2, 20000), nrows=10000)

【讨论】:

    【解决方案2】:

    我认为你可以使用nrows 参数。来自the docs

    nrows : int, default None
    
        Number of rows of file to read. Useful for reading pieces of large files
    

    这似乎有效。使用标准的大型测试文件之一(988504479 字节,5344499 行):

    In [1]: import pandas as pd
    
    In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
    CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
    Wall time: 0.00 s
    
    In [3]: len(z)
    Out[3]: 20
    
    In [4]: time z = pd.read_csv("P00000001-ALL.csv")
    CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
    Wall time: 30.23 s
    

    【讨论】:

    • 太棒了,一定是错过了那个参数。谢谢。
    • skiprows=None 也是一个需要记住的有用参数
    • 加载最后 n 行的最佳方法是什么?基本上tail()的作用,但我需要在加载csv时使用它。提前致谢!
    • @DanailPetrov:使用skiprows,类似于df = pd.read_csv(..., skiprows=total_rows - n, nrows=n)
    • 你能详细说明一下吗?在这种情况下,total_rows 是什么?自定义函数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 2022-12-13
    • 2020-04-26
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多