【发布时间】:2021-07-13 06:09:10
【问题描述】:
我有一个大的 csv 文件,我正在阅读它。在进程中间内存已满,所以我想从它离开的地方重新开始。我知道哪个块但不知道如何直接去那个块。
这是我尝试过的。
# data is the txt file
reader = pd.read_csv(data ,
delimiter = "\t",
chunksize = 1000
)
# Please see the code below. When my last process broke, i was 154 so I think it should
# start from 154000th line. This time I don't
# plan to read whole file at once so I have an
# end point at 160000
first = 154*1000
last = 160*1000
output_path = 'usa_hotspot_data_' + str(first) + '_' + str(last) + '.csv'
print("Output file: ", output_path)
try:
os.remove(output_path)
except OSError:
pass
# Read chunks and save to a new csv
for i,chunk in enumerate(reader):
if (i >= first and i<=last) :
< -- here I do something -- >
# Progress Bar to keep track
if (i% 1000 == 0):
print("#", end ='')
但是,这需要很长时间才能到达我想去的第 i 行。我怎样才能跳过它之前的阅读块并直接去那里?
【问题讨论】:
-
dask 可以成为这里的救星。参考docs.dask.org/en/latest/dataframe.html
-
可以使用skiprows参数:pandas.pydata.org/docs/reference/api/pandas.read_csv.html
标签: python pandas csv large-data chunks