Pandas获取数据的尺寸信息
Pandas
中获取数据的尺寸信息,比如我们有如下的Excel
数据:
我们可以使用如下代码来获取数据的整体尺寸信息:
1 2 3 4 5 6 7 8 9 10 11 12 | import pandas as pd file = pd.read_excel(r "C:Users15025Desktopuncledebug.xlsx" ) print ( file .size) print ( file .shape) print ( len ( file )) """ result: 55 (11, 5) 11 """ |
可以看到,结果与numpy
包中的结果类似,当我们的数据为二维时,使用size
获取到的是数据的整体大小,为行数量11
乘以列数量5
。
当我们使用shape
时,获取到的是二维数据行数量与列数量组成的一个元组(11, 5)
。
当我们使用len()
函数作用于二维数据时,我们获得的是行数量。
当数据为一维时,我们使用len()
函数获取的结果将会与使用size
获取到的结果一致。
pandas处理大数据信息
使用到的数据大小为130M
5 rows × 161 columns
1 2 3 | g1.shape #(171907, 161) #17W的数据,有161列 |
pandas 可以处理几千万,上亿的数据
打印出每种类型占的内存量
1 2 3 4 5 6 7 8 9 10 11 | for dtype in [ 'float64' , 'int64' , 'object' ]: selected_dtype = g1.select_dtypes(include = [dtype]) mean_usage_b = selected_dtype.memory_usage(deep = True ).mean() mean_usage_mb = mean_usage_b / 1024 * * 2 print ( '平均内存占用 ' ,dtype , mean_usage_mb) ''' deep : bool,默认为False 如果为True,则通过询问对象 dtype 来深入了解数据 的系统级内存消耗, 并将其包含在返回值中。 ''' |
让内存占用变小,int 类型从64 变为 32,在不影响使用的前提下
1 2 3 4 | #查看每种类型最大 能表示多大的数 int_types = [ 'uint8' , 'int8' , 'int16' , 'int32' , 'int64' ] for it in int_types: print (np.iinfo(it)) |
1 2 3 4 5 | g1_int = g1.select_dtypes(include = [ 'int64' ]) #生成一个只有int类型的DataFrame coverted_int = g1_int. apply (pd.to_numeric, downcast = 'unsigned' ) #apply 会将数据一条一条的读取,并传入目标进行执行 #int64 转换为了 unsigned |
1 2 3 4 5 | g1_float = g1.select_dtypes(include = [ 'float64' ]) #生成一个只有int类型的DataFrame coverted_floar = g1_int. apply (pd.to_numeric, downcast = 'float' ) #apply 会将数据一条一条的读取,并传入目标进行执行 #float64转换为了32 |
1 2 3 4 5 6 7 8 9 10 11 | import pandas as pd g1 = pd.read_csv( 'game_logs.csv' ) g1_obj = g1.select_dtypes(include = [ 'object' ]) g1.shape #(171907, 78) g1_obj.describe() #查看信息生成的介绍 #count 数量 #unique 不重复的值 #top #freq |
1 2 3 | dow = g1_obj.day_of_week dow_cat = dow.astype( 'category' ) dow_cat.head() |
优化str占用内存
1 2 3 4 5 6 | 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 |
1 2 3 4 | #时间格式,写成标准格式的是比较占用内存的 #可以转换时间格式 g1[ 'date' ] = pd.to_datetime(date, format = '%Y%m%d' ) #这种比较占用内存 |
结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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_usagee(deep = True ) usage_mb = usage_b / 1024 * * 2 return '{:03.2f} MB' . format (usage_mb) g1_int = g1.select_dtypes(include = [ 'int64' ]) #生成一个只有int类型的DataFrame coverted_int = g1_int. apply (pd.to_numeric, downcast = 'unsigned' ) #apply 会将数据一条一条的读取,并传入目标进行执行 #int64 转换为了 unsigned print (mem_usage(g1_int)) print (mem_usage(coverted_int)) |
7.87 MB
1.48 MB
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。