【发布时间】:2017-03-25 16:46:21
【问题描述】:
我正在使用 pandas 读取一个超大的 csv 文件(10G),并且 read_csv(filename, chunksize=chunksize) 返回一个迭代器(假设它命名为“reader”)。现在我想得到一个精确的块,因为我只想要几行(例如,我读取的 csv 文件有 1000000000 行,我想得到数字 50000000 行和它之后的 1000 行),我该怎么办除了遍历迭代器直到它到达我想要的块?
这是我以前的代码:
def get_lines_by_chunk(file_name, line_beg, line_end, chunk_size=-1):
func_name = 'get_lines_by_chunk'
line_no = get_file_line_no(file_name)
if chunk_size < 0:
chunk_size = get_chunk_size(line_no, line_beg, line_end)
reader = pd.read_csv(file_name, chunksize=chunk_size)
data = pd.DataFrame({})
flag = 0
for chunk in reader:
line_before = flag * chunk_size
flag = flag + 1
line_after = flag * chunk_size
if line_beg >= line_before and line_beg <= line_after:
if line_end >= line_after:
temp = chunk[line_beg - line_before : chunk_size]
data = pd.concat([data, temp], ignore_index=True)
else:
temp = chunk[line_beg - line_before : line_end - line_before]
data = pd.concat([data, temp], ignore_index=True)
return data
elif line_end <= line_after and line_end >= line_before:
temp = chunk[0 : line_end - line_before]
data = pd.concat([data, temp], ignore_index=True)
return data
elif line_beg < line_before and line_end > line_after:
temp = chunk[0 : chunk_size]
data = pd.concat([data, temp], ignore_index=True)
return data
【问题讨论】:
-
你不能只做
df = pd.read_csv(file_name, skiprows=50000000, nrows=1000)吗? -
哦...它似乎有效,我是熊猫新手..
-
标题 "How to get an exact one of python iterator?" 对我来说没有任何意义。可以改写吗?
-
我的意思是 pandas.read_csv 在为其分配块大小时返回一个迭代器'i',我想要 i.next().next().next()...(例如 500 个next) 没有 500 次迭代,而是像数组一样直接获取操作...
标签: python csv pandas dataframe io