什么是空值提升
当列中有空值时,列的原有类型会被忽略,同时会被提升到一个更『宽』或更『高』的类型来存储空值。
原始类型 | 提升到的类型用于存储空值(Promotion dtype for storing NAs) |
---|---|
| no change |
| no change |
| cast to |
| cast to |
空值提升的不利影响
这有什么潜在的影响?空值提升有可能会提升内存开销。
如何消除不利影响
1、创建一个csv文件data.csv,存储以下内容。
id,name,age
1,lily,18
2,lucy,19
3,tom,NaN
4,jim,nan
2、使用如下方式加载csv文件,并查看内存情况。
# 加载文件
df1=pd.read_csv("data.csv")
# 查看内存占用情况
df1.info(memory_usage="deep")
# 输出
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 4 non-null int64
1 name 4 non-null object
2 age 2 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 434.0 bytes
age本是一个int类型,结果被提升为float64类型;用64位来存储,有些大材小用了。
3、指定兼容空值的类型
为了表示可能缺少值的整数列,pandas提供了可空的整数扩展类:
Int8Dtype
Int16Dtype
Int32Dtype
Int64Dtype
df = pd.read_csv("data.csv",dtype={'id':pd.Int64Dtype(),'name':object,'age':pd.Int8Dtype()})
df.info(memory_usage='deep')
#输出
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 4 non-null Int64
1 name 4 non-null object
2 age 2 non-null Int8
dtypes: Int64(1), Int8(1), object(1)
memory usage: 414.0 bytes
内存使用从434bytes 降到了414bytes。