Pandas 数据帧memory_usage()方法

原文:https://www.studytonight.com/pandas/pandas-dataframe-memory_usage-method

在本教程中,我们将学习 PandasDataFrame.memory_usage()的方法。此方法以字节为单位返回每列的内存使用情况,即每列容纳多少字节。在数据帧上应用此方法后,它将返回 Series,其中索引是数据帧的列名,值是每列的内存使用量(以字节为单位)。

下图显示了DataFrame.memory_usage()方法的语法。

语法

使用这些方法所需的语法如下

DataFrame.memory_usage(index=True, deep=False)

因素

索引:表示 bool(真或假),默认值为 True。它主要指定在返回 Series 时是否包括数据帧索引的内存使用情况。如果 index=True,则索引的内存使用量是输出中的第一项。

deep: 表示 bool(真或假),默认值为 False。如果这是真的,则通过询问对象数据类型的系统级内存消耗来深入检查数据,并将它们包含在返回值中。

示例:使用DataFrame.memory_usage()方法获取内存使用情况

在下面的例子中,DataFrame.memory_usage()方法返回数据帧各列使用的内存,包括数据帧索引的内存使用情况。

#importing pandas as pd
import pandas as pd
#creating the DataFrame
df = pd.DataFrame([['Abhishek',100], ['Anurag',101],['Divya',104]], columns=['Name', 'Roll No'], index=[1,2,3])
print("----------The DataFrame is---------")
print(df)
print("-----------------------------------")
print(df.memory_usage())

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- 名称卷号 1 Abhishek 100 2 Anurag 101 3 Divya 104 - 索引 24 名称 24 卷号 24 数据类型:int64

示例:在DataFrame.memory_usage()方法中设置索引=假

在下面的例子中,DataFrame.memory_usage() 方法返回数据帧的列所使用的内存,这不包括数据帧索引所使用的内存。

#importing pandas as pd
import pandas as pd
#creating the DataFrame
df = pd.DataFrame({'int64':[24,45,78,45],'float64':[1.5,2.5,7.8,4.5]})
print("----------The DataFrame is---------")
print(df)
print("-----------------------------------")
print(df.memory_usage(index=False))

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- int64 float 64 0 24 1.5 1 45 2.5 2 78 7.8 3 45 4.5 - int 64 32 float 64 32 数据类型:int 64

示例:按数据帧获取总体内存消耗

我们可以使用DataFrame.memory_usage() 方法和 sum()函数获得数据帧列的总内存消耗。下面的例子显示了同样的情况。

#importing pandas as pd
import pandas as pd
#creating the DataFrame
df = pd.DataFrame({'int64':[24,45,78],'float64':[2.5,7.8,4.5]})
print("----------The DataFrame is---------")
print(df)
print("------------------------------------")
print(df.memory_usage(index=False))
print("-----------------------------------")
print("The total memory used by the DataFrame column's is:",df.memory_usage(index=False).sum())

一旦我们运行该程序,我们将获得以下输出。

-数据帧为- int 64 float 64 0 24 2.5 1 45 7.8 2 78 4.5 - int 64 24 float 64 24 数据类型:int64 - 数据帧列使用的总内存为:48

结论

在本教程中,我们学习了 PythonPandasDataFrame.memory_usage() 法。我们通过解例题了解语法,获取内存使用信息。