pandas 中處理大型檔案的方法
阿新 • • 發佈:2020-12-07
import pandas as pd
import numpy as np
讀取資料
g1=pd.read_csv(r"F:\_test.csv")
g1
查看錶的行列資訊,有多少行,多少列
g1.shape
查看錶的記憶體資訊
g1.info(memory_usage="deep")
檢視不同內型別所佔用的記憶體空間大小
for dtype in ["float64","int64","object"]:
selected_type= g1.select_dtypes(include=[dtype])
mean_usage_b=selected_type.memory_usage(deep=True)
mean_usage_mb=mean_usage_b/1024**2
print("平均佔用記憶體:",dtype,mean_usage_mb)
定義一個函式,來判定輸入的資料大小
def mem_usage(pandas_obj):
if isinstance(pandas_obj,pd.DataFrame):
usage_b=pandas_obj. memory_usage(deep=True).sum()
else:
usage_b=pandas_obj.memory_usage(deep=True)
usage_mb=usage_b/1024**2
return '{:03.2f}MB'.format(usage_mb)
針對 int 型別進行向下轉換 downcast
選擇目標表中 字元型別為int64的列
g1_int=g1.select_dtypes(include=['int64'])
將對應的列,進行向下轉換
coverted_int=g1_int.apply(pd.to_numeric, downcast='unsigned')
###判定未轉換前的資料大小
print(mem_usage(g1_int))
###判定已轉換的資料大小
print(mem_usage(coverted_int))
針對float 型別進行向下轉換
選擇目標表中 字元型別為float64的列
g1_float=g1.select_dtypes(include=[‘float64’])
將對應的列,進行向下轉換
coverted_float=g1_float.apply(pd.to_numeric,downcast='unsigned')
###判定未轉換前的資料大小
print(mem_usage(g1_float))
###判定已轉換的資料大小
print(mem_usage(coverted_float))
複製一個表,將轉換的列進行
optimized_g1=g1.copy()
optimized_g1[coverted_int.columns]=coverted_int
optimized_g1[coverted_float.columns]=coverted_float
針對整個表進行比對,看資料是否有真的進行縮減
print(mem_usage(g1))
print(mem_usage(optimized_g1))
結論 通過int64 轉int32 ,或者float64 轉float32 可以將資料進行一定的縮減,但是效果並不是很明顯
obj字串中,該型別的佔比較大,縮減可以主要通過他來進行儲存進行縮減
賽選出所有字串的欄位出來
g1_obj=g1.select_dtypest_dtypes(include=[“object”]).copy()
針對字串的進行描述
g1_obj.describe()
判定 當 unique 數值 遠遠小於 count 的數值時候,可以將設定記憶體地址–category,減少空間使用
dow_starting_street=g1_obj.starting_street.astype('category')
dow_starting_end_street=g1_obj.end_street.astype('category')
dow_starting_street_for_each_step=g1_obj.street_for_each_step.astype('category')
dow_starting_step_maneuvers=g1_obj.step_maneuvers.astype('category')
##
##轉換前的資料大小
print(mem_usage(g1_obj.starting_street))
##轉換後的資料大小
print(mem_usage(dow_starting_street))
定義一個函式,將所有的列進行字串的大小轉換
converted_obj=pd.DataFrame()
##遍歷在字串裡面的每行資料
for col in g1_obj.columns:
###判定改行去重後的所剩的數值
num_unique_values=len(g1_obj[col].unique())
# 判定不去重的列的數值剩多少
num_total_values=len(g1_obj[col])
if num_unique_values/num_total_values<0.7:
##如果去重後的佔比小於0.7 就可以進行轉換為為category
converted_obj.loc[:,col]=g1_obj[col].astype("category")
else:
converted_obj.loc[:,col]=g1_obj[col]
效果轉換明顯
##對比轉換以及未轉換的資料空間所佔大小
print(mem_usage(g1_obj))
print(mem_usage(converted_obj))