簡體   English   中英

如何使用 pandas 將大型 csv 文件轉儲到表中?

[英]How to dump a large csv file to a table using pandas?

我有一個大小超過1 GBcsv文件。 通常這就是我使用pandascsv轉換為table的方式。

import pandas as pd
from sqlalchemy import create_engine

file_path = "/path/to/test.csv"
df = pd.read_csv(file_path)

for col in df.columns:
    # convert each column values to numeric 
    df[col] = pd.to_numeric(df[col], errors='coerce')

engine = create_engine('postgresql://username:password@localhost:port/dbname')
df.to_sql("mytable", engine)

如您所見,我加載了csv文件,對每一column執行操作並將其轉儲到table

現在由於我的文件非常大, pandas無法將其加載到data frame 所以我在網上查找了一個解決方案,它談到了以塊加載data並執行操作使用 pandas 有效地讀取大型 CSV 文件而不會崩潰 所以這就是我想出的

file_path = "/path/to/test.csv" 
chunksize = 100000
for chunk in pd.read_csv(file_path, chunksize=chunksize, iterator=True, low_memory=False):
    columns = chunk.columns

它給了我每個塊的columns 那么塊大小是否意味着它一次讀取n行? 我不太清楚如何確保覆蓋所有塊並繼續將data附加到table中,以便最終將所有data轉儲到table ,就像使用較小的csv文件一樣?

可以在此處找到有關iteratorchunksize大小的更新文檔: 逐塊迭代文件

那么塊大小是否意味着它一次讀取n行?

是的。

您使用chunksize的代碼大部分是正確的,您只需將每個塊添加到 dataframe 中。

如果您的所有列都是相同類型並且不需要任何特殊邏輯/類型,則轉換整個 DataFrame 而不是逐列進行。 或者,您可以將dtypes指定為read_csv 但是,您將無法指定'coerce' ,因此將保持原樣。

對於非常大的數據,最好分塊進行整個讀取,轉換,to_sql。 另請注意,在這種情況下使用low_memory=False是沒有意義的,請使用默認的True 無論如何,您稍后都會轉換類型,因此混合類型推斷(這可能會發生)無關緊要。

engine = create_engine('postgresql://username:password@localhost:port/dbname')
reader = pd.read_csv(file_path, chunksize=chunksize, low_memory=True)
for rows in reader:
    df = pd.DataFrame(rows)
    # column conversions
    for col in df.columns:
        df[col] = pd.to_numeric(df[col], errors='coerce')
    # sql export
    df.to_sql("mytable", engine)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM