【问题标题】:Why does memory usage in Pandas report the same number for integers as for object dtype?为什么 Pandas 中的内存使用情况报告整数与对象 dtype 相同的数字?
【发布时间】:2019-04-18 17:37:45
【问题描述】:

我正在尝试了解 Pandas 中整数和字符串(对象)数据类型在内存使用方面的差异。

import pandas as pd
df_int = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'), dtype=int)

正如预期的那样,这需要大约 3.2 KB 的内存,因为每列是一个 64 位整数

In [38]: df_int.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100 entries, 0 to 99
Data columns (total 4 columns):
A    100 non-null int64
B    100 non-null int64
C    100 non-null int64
D    100 non-null int64
dtypes: int64(4)
memory usage: 3.2 KB

但是,当我尝试将其初始化为字符串时,它告诉我它的内存使用量大致相同

import pandas as pd
df_str = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'), dtype=str)

In [40]: df_str.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100 entries, 0 to 99
Data columns (total 4 columns):
A    100 non-null object
B    100 non-null object
C    100 non-null object
D    100 non-null object
dtypes: object(4)
memory usage: 3.2+ KB

当我使用sys.getsizeof 时,区别很明显。对于仅包含 64 位整数的数据帧,大小约为 3.3 KB(包括 24 字节的数据帧开销)

In [44]: sys.getsizeof(df_int)
Out[44]: 3304

对于使用转换为字符串的整数初始化的数据帧,它接近 24 KB

In [42]: sys.getsizeof(df_str)
Out[42]: 23984

为什么 Pandas 中的内存使用情况报告整数与字符串(对象 dtype)相同的数字?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    按照docs,使用'deep'获取实际值(否则为估计值)

    df_str.info(memory_usage='deep')
    #<class 'pandas.core.frame.DataFrame'>
    #RangeIndex: 100 entries, 0 to 99
    #Data columns (total 4 columns):
    #A    100 non-null object
    #B    100 non-null object
    #C    100 non-null object
    #D    100 non-null object
    #dtypes: object(4)
    #memory usage: 23.3 KB
    

    “deep”的值相当于“True with deep introspection”。 内存使用以人类可读的单位(base-2 表示)显示。 没有深入的反省,内存估计是基于列 dtype 和行数假设值消耗相同的内存 对应 dtypes 的数量。通过深度记忆内省,一个 实际内存使用计算是以 计算资源。

    【讨论】:

    • 回答我的问题。谢谢。
    猜你喜欢
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2012-11-25
    • 2015-02-27
    • 2012-12-30
    • 2015-03-23
    • 1970-01-01
    相关资源
    最近更新 更多