python - 使用 pandas 删除数据行会增加内存使用量
问题描述
我有一个客户数据集,其中包含三列、一个键以及一个表示客户坐标的 X 和 Y。
In [1]: customers
Out[1]:
key X Y
0 b305b0b7-fb24-4eef-9055-827cf7f39b93 NaN NaN
1 edf5e4bc-d553-4285-9de3-45165f96dd02 987269.0 6236836.0
2 00ded895-ae97-4d27-b317-91c6931662b7 880460.0 6267799.0
3 d957d117-72db-444f-ac9a-338c2034f5db 830645.0 6287647.0
4 ac504435-7eb8-4275-a3da-6f673ff324ae 837826.0 6293434.0
customers.info()
返回:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 378195 entries, 0 to 378194
Data columns (total 3 columns):
cle 378195 non-null object
X 375850 non-null float64
Y 375850 non-null float64
dtypes: float64(2), object(1)
memory usage: 8.7+ MB
我只使用以下方法保留具有 X 和 Y 值(不是NaN
)的数据点:
customers2 = customers[customers['X'].notna() & customers['Y'].notna()]
它删除NaN
了 X 或 Y 中的任何行(索引 0 的示例)。
In [2]: customers2
Out[2]:
cle X Y
1 edf5e4bc-d553-4285-9de3-45165f96dd02 987269.0 6236836.0
2 00ded895-ae97-4d27-b317-91c6931662b7 880460.0 6267799.0
3 d957d117-72db-444f-ac9a-338c2034f5db 830645.0 6287647.0
4 ac504435-7eb8-4275-a3da-6f673ff324ae 837826.0 6293434.0
5 5d4c8fe0-56ce-4498-a4ee-2fd4314abc1e 987025.0 6427374.0
但是这个新数据帧的信息显示了更高的内存使用率,尽管条目数量有所减少(从最初的 378195 减少到 375850):
In [2]: customers2.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 375850 entries, 1 to 378194
Data columns (total 3 columns):
cle 375850 non-null object
X 375850 non-null float64
Y 375850 non-null float64
dtypes: float64(2), object(1)
memory usage: 11.5+ MB
我无法解释为什么,即使我可以customers2
像普通数据框一样继续操作。
有什么解释吗?谢谢。
解决方案
我会说你的记忆指数因为你的指数而增加,在你之前:
RangeIndex: 378195 entries, 0 to 378194
之后:
Int64Index: 375850 entries, 1 to 378194
Int64Index 每个条目占用 8 个字节。
这是 RangeIndex:https ://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.RangeIndex.html
您可以将其转换回来,如:
customers2.index = pd.RangeIndex(start=0, stop=len(customers2), step=1)
推荐阅读
- ios - iPhone 未从 AppleWatch 接收 applicationContext
- python-3.x - python重新打开并将数据写入现有文件(文件名由用户先前的输入给出)
- java - 如何在 Spring 的单个事务中使用多个数据源(一个用于读取,另一个用于写入)?
- javascript - Javascript:
如果找到特殊字符则添加 - c++ - 如何检查模板参数化回调函数签名是一种
- c# - 按 smalldatetime 字段排序在 SQL Server 和 C#(实体框架)中产生不同的结果
- php - 课堂内准备好的语句不起作用
- java - 如何修复被忽略的嵌入式对象中的验证约束?
- apache-kafka - logstash kafka 输入具有不同编解码器的多个主题
- c# - 在方法调用 C# WPF 之后设置组合框所需的索引