使用疊代器載入大型檔案到記憶體

Python 工具箱

Hugo Bowne-Anderson

Data Scientist at DataCamp

分塊載入資料

  • 資料可能大到無法放進記憶體
  • 解法:分塊載入資料!
  • pandas 函式:read_csv()
    • 指定分塊大小:chunksize
Python 工具箱

遍歷資料

import pandas as pd
result = []

for chunk in pd.read_csv('data.csv', chunksize=1000):
result.append(sum(chunk['x']))
total = sum(result)
print(total)
4252532
Python 工具箱

遍歷資料

import pandas as pd
total = 0

for chunk in pd.read_csv('data.csv', chunksize=1000): total += sum(chunk['x'])
print(total)
4252532
Python 工具箱

一起來練習吧!

Python 工具箱

Preparing Video For Download...