【发布时间】:2019-03-02 19:21:26
【问题描述】:
在我的 ML 项目中,我开始遇到 10 Gb+ 大小的 csv 文件,因此我正在尝试实施一种有效的方法来从我的 csv 文件中获取特定行。
这让我发现了itertools(据说它可以有效地跳过csv.reader 的行,而循环遍历它会加载它经过的每一行到内存中),并按照this 回答我尝试了以下:
import collections
import itertools
with open(csv_name, newline='') as f:
## Efficiently find total number of lines in csv
lines = sum(1 for line in f)
## Proceed only if my csv has more than just its header
if lines < 2:
return None
else:
## Read csv file
reader = csv.reader(f, delimiter=',')
## Skip to last line
consume(reader, lines)
## Output last row
last_row = list(itertools.islice(reader, None, None))
consume() 存在
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(itertools.islice(iterator, n, n), None)
但是,我只从last_row 得到一个空列表,这意味着出了点问题。
我正在测试此代码的短 csv:
Author,Date,Text,Length,Favorites,Retweets
Random_account,2019-03-02 19:14:51,twenty-two,10,0,0
我哪里错了?
【问题讨论】:
-
熊猫不能满足你的需求吗? pandas.pydata.org/pandas-docs/stable/reference/api/…
-
不,因为 pandas 需要大约几分钟才能为我加载整个 csv,而我通常只需要它们的特定行(在我上面的示例中,最后一行)。
-
你需要一个换行偏移索引。因此,您可以在不读取文件的情况下查找给定行。
-
循环遍历它不会将每一行都加载到内存中。它一次加载一行,因此最多只需要最大行的内存开销。
标签: python loops csv file-io iterator