pandas.DataFrame.memory_usage#
- DataFrame.memory_usage(index=True, deep=False)[source]#
返回每列的内存使用量(以字节为单位)。
内存使用量可以选择性地包含索引和 object 数据类型元素的贡献。
此值默认在 DataFrame.info 中显示。可以通过将
pandas.options.display.memory_usage设置为 False 来禁止显示。- 参数:
- indexbool, 默认 True
指定是否在返回的 Series 中包含 DataFrame 索引的内存使用量。如果
index=True,则索引的内存使用量是输出中的第一项。- deepbool, default False
如果为 True,则通过查询 object 数据类型以获取系统级内存消耗来深入检查数据,并将其包含在返回值中。
- 返回:
- Series
一个 Series,其索引是原始列名,其值是每列的内存使用量(以字节为单位)。
另请参阅
numpy.ndarray.nbytesndarray 元素消耗的总字节数。
Series.memory_usageSeries 消耗的字节数。
Categorical具有许多重复值的字符串值的内存高效数组。
DataFrame.infoDataFrame 的简洁摘要。
注意
有关更多详细信息,请参阅 常见问题解答。
示例
>>> dtypes = ["int64", "float64", "complex128", "object", "bool"] >>> data = dict([(t, np.ones(shape=5000, dtype=int).astype(t)) for t in dtypes]) >>> df = pd.DataFrame(data) >>> df.head() int64 float64 complex128 object bool 0 1 1.0 1.0+0.0j 1 True 1 1 1.0 1.0+0.0j 1 True 2 1 1.0 1.0+0.0j 1 True 3 1 1.0 1.0+0.0j 1 True 4 1 1.0 1.0+0.0j 1 True
>>> df.memory_usage() Index 132 int64 40000 float64 40000 complex128 80000 object 40000 bool 5000 dtype: int64
>>> df.memory_usage(index=False) int64 40000 float64 40000 complex128 80000 object 40000 bool 5000 dtype: int64
默认情况下,将忽略 object 数据类型列的内存占用。
>>> df.memory_usage(deep=True) Index 132 int64 40000 float64 40000 complex128 80000 object 180000 bool 5000 dtype: int64
使用 Categorical 来高效存储具有许多重复值的 object-dtype 列。
>>> df["object"].astype("category").memory_usage(deep=True) 5140