pandas内存优化

在使用Pandas 处理IPGeo 数据时,发现在云服务器上无法执行,总是被系统 Killed . 排查系统日志 确认是 内存溢出被系统沙雕了.
然后在查询相关资料,Linux 下的 OOM 机制:

egrep -i -r 'killed process' /var/log

接下来先提高运行环境的内存吧, 当前是 8G 内存,换 16G 的内存之后还是 Killed

numpy.core._exceptions.MemoryError: Unable to allocate 843. MiB for an array with shape (4, 27639374) and data type object

修改下系统设置吧:

echo 1 > /proc/sys/vm/overcommit_memory
启用内存过载模式,无论有多大都允许分配

再次执行:

numpy.core._exceptions.MemoryError: Unable to allocate 843. MiB for an array with shape (4, 27639374) and data type object

没办法,去优化代码吧:

  1. 分片读取后的数据 100w =》 850M 左右, 先删除不要的字段再合并,650M
  2. 设置读取字段为指定类型: 最重要的是 category ; 250M

引申问题:

  1. 空值填充 fillna 无法在 category 类型上填充不存在的 数据.
  2. 主动清理系统内存缓存
    • echo 1 > /proc/sys/vm/drop_caches
    • echo 0 > /proc/sys/vm/drop_caches

1.Unable to allocate 843. MiB for an array with shape
2.Can only use .cat accessor with a ‘category’ dtype”
3.fill value must be in categories pandas
4.Pandas: ValueError: Integer column has NA values in column 2
5.int<=>ip