Pandas如何获取数据的尺寸信息

来自:网络
时间:2024-03-18
阅读:

Pandas获取数据的尺寸信息

Pandas中获取数据的尺寸信息,比如我们有如下的Excel数据:

Pandas如何获取数据的尺寸信息

我们可以使用如下代码来获取数据的整体尺寸信息:

import pandas as pd

file = pd.read_excel(r"C:\Users\15025\Desktop\uncle\debug.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

g1.shape
#(171907, 161)
#17W的数据,有161列

pandas 可以处理几千万,上亿的数据

打印出每种类型占的内存量

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,在不影响使用的前提下

#查看每种类型最大 能表示多大的数
int_types = ['uint8','int8','int16','int32','int64']
for it in int_types:
    print(np.iinfo(it))
g1_int = g1.select_dtypes(include = ['int64'])
#生成一个只有int类型的DataFrame
coverted_int = g1_int.apply(pd.to_numeric, downcast='unsigned')
#apply 会将数据一条一条的读取,并传入目标进行执行
#int64 转换为了 unsigned
g1_float = g1.select_dtypes(include = ['float64'])
#生成一个只有int类型的DataFrame
coverted_floar = g1_int.apply(pd.to_numeric, downcast='float')
#apply 会将数据一条一条的读取,并传入目标进行执行
#float64转换为了32
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
dow = g1_obj.day_of_week
dow_cat = dow.astype('category')
dow_cat.head()

优化str占用内存

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.5:
        converted_obj.loc[:,col] = g1_obj[col].astype('category')
    else:
        converted_obj.loc[:,col] = g1_obj[col]
#时间格式,写成标准格式的是比较占用内存的
#可以转换时间格式
g1['date'] = pd.to_datetime(date,format='%Y%m%d')
#这种比较占用内存

结果:

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

返回顶部
顶部