1. 程式人生 > 其它 >Python 大檔案拆分,分類,儲存

Python 大檔案拆分,分類,儲存

技術標籤:大檔案讀取大檔案拆分大檔案儲存pythonpandas

Python 大檔案拆分,分類,儲存

一、對可迭代物件簡易理解

我們以 hello word字串進行試驗:

————————————————————————————————————————————————————————
# method1:
lst_iter = iter('hello world')   # 用iterate() 生成迭代器
for i in lst_iter:
    print(i)
————————————————————————————————————————————————————————
# method2:
lst_iter =
iter('hello world') loop = True while loop: try: print(next(lst_iter)) except StopIteration: loop = False ———————————————————————————————————————————————————————— # method1 和 method2 執行結果一致為: h e l l o w o r l d

二、進行大檔案的拆分,儲存

需要使用 pandas模組中 chunksize或者iterator引數, 還需使用groupby() 方法。

# 演示案例  <可迭代物件,進行遍歷>
lst_iter = iter('hello')
print(next(lst_iter))
print('***********************')
for i in lst_iter:
    print(i)
————————————————————————————————————————————————————————
# 執行結果
h
***********************
e
l
l
o
import pandas as pd
import numpy as np

# 逐步讀取檔案
table = pd.read_csv
(r'D:\Program Files\vscodeworkspace\鐳射雷達\ 原始資料\WindSpeed20181028.csv', index_col=0, chunksize=1600) ''' 對儲存檔案的資料進行重新寫入,防止重複執行,追加在原有資料上 ''' df = next(table) groupby = df.groupby(by='Distance') # 分組 for value, group in groupby: filename = './拆分資料/' + str(value) + '.csv' # 命名 ''' 取出第一個 部分資料,寫入儲存 header ''' group.to_csv(filename, sep=',', mode='w') # 儲存 for df in table: groupby = df.groupby(by='Distance') for value, group in groupby: filename = './拆分資料/' + str(value) + '.csv' ''' for 迴圈追加不需要 header,需要申明 ''' group.to_csv(filename, sep=',', header=None, mode='a') # 儲存

參考

撰寫 參考了 python使用chunk進行大檔案的讀寫,程式碼如下:

# python使用chunk進行大檔案的讀寫
reader = pd.read_csv('test.csv', iterator=True,low_memory=False)
loop = True
chunkSize = 100000
chunks = []
while loop:
    try:
        chunk = reader.get_chunk(chunkSize)
        chunks.append(chunk)
    except StopIteration:
        loop = False
        print("迭代停止。")
df = pd.concat(chunks, ignore_index=True)