python - 为什么 Pandas 中的内存使用报告整数的数量与对象 dtype 的数量相同?

标签 python pandas

我试图了解 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

对于用整数转换为字符串初始化的dataframe,将近24 KB

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

为什么 Pandas 中的内存使用报告整数和字符串(对象数据类型)的数量相同?

最佳答案

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

A value of ‘deep’ is equivalent to “True with deep introspection”. Memory usage is shown in human-readable units (base-2 representation). Without deep introspection a memory estimation is made based in column dtype and number of rows assuming values consume the same memory amount for corresponding dtypes. With deep memory introspection, a real memory usage calculation is performed at the cost of computational resources.

关于python - 为什么 Pandas 中的内存使用报告整数的数量与对象 dtype 的数量相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55751180/

相关文章:

python - 返回类实例的抽象类方法的键入提示

python - python中的循环依赖

python - Sklearn 中的数据类型和机器学习算法

python - 按列时间值过滤 pandas DataFrame

python - pandas 将列添加到列底部

python - 为 pandas 数据框列向量化 HumanName 库

python - 使用 boto3、Python 从 S3 存储桶查找最新的 CSV 文件

python - 如何使用 python/django 从 gmail 或 yahoo 等各种服务导入联系人

python - 如何在列表理解中执行多个操作

python - epoll +非阻塞套接字比阻塞+超时慢吗?