如何减少 pandas DataFrame 的内存?

2023-11-23

我在日常工作中使用 pandas,并且我使用的一些数据框非常大(大约数亿行乘以数百列)。有什么方法可以减少 RAM 内存消耗吗?


您可以使用此功能。它通过将数据类型限制为每列所需的最小值来减少数据的大小。

该代码不是我的,我从以下链接复制了它,并根据我的需要进行了调整。https://www.mikulskibartosz.name/how-to-reduce-memory-usage-in-pandas/

def reduce_mem_usage(df, int_cast=True, obj_to_category=False, subset=None):
    """
    Iterate through all the columns of a dataframe and modify the data type to reduce memory usage.
    :param df: dataframe to reduce (pd.DataFrame)
    :param int_cast: indicate if columns should be tried to be casted to int (bool)
    :param obj_to_category: convert non-datetime related objects to category dtype (bool)
    :param subset: subset of columns to analyse (list)
    :return: dataset with the column dtypes adjusted (pd.DataFrame)
    """
    start_mem = df.memory_usage().sum() / 1024 ** 2;
    gc.collect()
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))

    cols = subset if subset is not None else df.columns.tolist()

    for col in tqdm(cols):
        col_type = df[col].dtype

        if col_type != object and col_type.name != 'category' and 'datetime' not in col_type.name:
            c_min = df[col].min()
            c_max = df[col].max()

            # test if column can be converted to an integer
            treat_as_int = str(col_type)[:3] == 'int'
            if int_cast and not treat_as_int:
                treat_as_int = check_if_integer(df[col])

            if treat_as_int:
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.uint8).min and c_max < np.iinfo(np.uint8).max:
                    df[col] = df[col].astype(np.uint8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.uint16).min and c_max < np.iinfo(np.uint16).max:
                    df[col] = df[col].astype(np.uint16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.uint32).min and c_max < np.iinfo(np.uint32).max:
                    df[col] = df[col].astype(np.uint32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)
                elif c_min > np.iinfo(np.uint64).min and c_max < np.iinfo(np.uint64).max:
                    df[col] = df[col].astype(np.uint64)
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)
        elif 'datetime' not in col_type.name and obj_to_category:
            df[col] = df[col].astype('category')
    gc.collect()
    end_mem = df.memory_usage().sum() / 1024 ** 2
    print('Memory usage after optimization is: {:.3f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))

    return df
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何减少 pandas DataFrame 的内存? 的相关文章

  • SQLAlchemy 通过关联对象声明式多对多自连接

    我有一个用户表和一个朋友表 它将用户映射到其他用户 因为每个用户可以有很多朋友 这个关系显然是对称的 如果用户A是用户B的朋友 那么用户B也是用户A的朋友 我只存储这个关系一次 除了两个用户 ID 之外 Friends 表还有其他字段 因此
  • 将 saxon 与 python 结合使用

    我需要使用 python 处理 XSLT 目前我正在使用仅支持 XSLT 1 的 lxml 现在我需要处理 XSLT 2 有没有办法将 saxon XSLT 处理器与 python 一起使用 有两种可能的方法 设置一个 HTTP 服务 接受
  • 将数据从 python pandas 数据框导出或写入 MS Access 表

    我正在尝试将数据从 python pandas 数据框导出到现有的 MS Access 表 我想用已更新的数据替换 MS Access 表 在 python 中 我尝试使用 pandas to sql 但收到错误消息 我觉得很奇怪 使用 p
  • 将 Matplotlib 误差线放置在不位于条形中心的位置

    我正在 Matplotlib 中生成带有错误栏的堆积条形图 不幸的是 某些层相对较小且数据多样 因此多个层的错误条可能重叠 从而使它们难以或无法读取 Example 有没有办法设置每个误差条的位置 即沿 x 轴移动它 以便重叠的线显示在彼此
  • 如何在flask中使用g.user全局

    据我了解 Flask 中的 g 变量 它应该为我提供一个全局位置来存储数据 例如登录后保存当前用户 它是否正确 我希望我的导航在登录后在整个网站上显示我的用户名 我的观点包含 from Flask import g among other
  • Python - StatsModels、OLS 置信区间

    在 Statsmodels 中 我可以使用以下方法拟合我的模型 import statsmodels api as sm X np array 22000 13400 47600 7400 12000 32000 28000 31000 6
  • python 相当于 R 中的 get() (= 使用字符串检索符号的值)

    在 R 中 get s 函数检索名称存储在字符变量 向量 中的符号的值s e g X lt 10 r lt XVI s lt substr r 1 1 X get s 10 取罗马数字的第一个符号r并将其转换为其等效整数 尽管花了一些时间翻
  • 是否可以忽略一行的pyright检查?

    我需要忽略一行的pyright 检查 有什么特别的评论吗 def create slog group SLogGroup data Optional dict None SLog insert one SLog group group da
  • Flask如何获取请求的HTTP_ORIGIN

    我想用我自己设置的 Access Control Allow Origin 标头做出响应 而弄清楚请求中的 HTTP ORIGIN 参数在哪里似乎很混乱 我在用着烧瓶 0 10 1 以及HTTP ORIGIN似乎是这个的特点之一object
  • 在Python中获取文件描述符的位置

    比如说 我有一个原始数字文件描述符 我需要根据它获取文件中的当前位置 import os psutil some code that works with file lp lib open path to file p psutil Pro
  • IO 密集型任务中的 Python 多线程

    建议仅在 IO 密集型任务中使用 Python 多线程 因为 Python 有一个全局解释器锁 GIL 只允许一个线程持有 Python 解释器的控制权 然而 多线程对于 IO 密集型操作有意义吗 https stackoverflow c
  • 在f字符串中转义字符[重复]

    这个问题在这里已经有答案了 我遇到了以下问题f string gt gt gt a hello how to print hello gt gt gt f a a gt gt gt f a File
  • 无法在 Python 3 中导入 cProfile

    我试图将 cProfile 模块导入 Python 3 3 0 但出现以下错误 Traceback most recent call last File
  • Fabric env.roledefs 未按预期运行

    On the 面料网站 http docs fabfile org en 1 10 usage execution html 给出这个例子 from fabric api import env env roledefs web hosts
  • 有人用过 Dabo 做过中型项目吗? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我们正处于一个新的 ERP 风格的客户端 服务器应用程序的开始阶段 该应用程序是作为 Python 富客户端开发的 我们目前正在评估 Dabo
  • Conda SafetyError:文件大小不正确

    使用创建 Conda 环境时conda create n env name python 3 6 我收到以下警告 Preparing transaction done Verifying transaction SafetyError Th
  • 如何计算 pandas 数据帧上的连续有序值

    我试图从给定的数据帧中获取连续 0 值的最大计数 其中包含来自 pandas 数据帧的 id date value 列 如下所示 id date value 354 2019 03 01 0 354 2019 03 02 0 354 201
  • 使用其构造函数初始化 OrderedDict 以便保留初始数据的顺序的正确方法?

    初始化有序字典 OD 以使其保留初始数据的顺序的正确方法是什么 from collections import OrderedDict Obviously wrong because regular dict loses order d O
  • 发送用户注册密码,django-allauth

    我在 django 应用程序上使用 django alluth 进行身份验证 注册 我需要创建一个自定义注册表单 其中只有一个字段 电子邮件 密码将在服务器上生成 这是我创建的表格 from django import forms from
  • 如何将输入读取为数字?

    这个问题的答案是社区努力 help privileges edit community wiki 编辑现有答案以改进这篇文章 目前不接受新的答案或互动 Why are x and y下面的代码中使用字符串而不是整数 注意 在Python 2

随机推荐

  • IE+溢出:隐藏

    我不知道这是一个问题还是错误 但是当我使用时overflow hidden 在IE中选择文本并将光标移动到页面底部 页面正在滚动 我尝试了IE9 IE11 当我使用 Firefox Opera Chrome Safari 时 页面不滚动 我
  • 'str' 对象没有 Python 中 Tensorflow 的属性 'decode' [重复]

    这个问题在这里已经有答案了 我想运行一段代码 它是使用 Tensorflow 用 Python3 编写的 我可以运行代码 但是当代码运行时 我尝试在单独的 Anaconda Prompt 中运行另一个代码并进行一些更改 然后我停止了代码 现
  • 双手柄滑块android [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 I was wondering if anyone had some code or knew of a place that has code f
  • 如何为 Firestore 中的不同字段组合创建索引?

    假设我有一个users我想在我的页面中过滤的集合 要过滤的字段是name age location 为此 我创建了一个复合索引 姓名 年龄 位置 问题是我希望有机会按 3 个名称的任意组合进行过滤 姓名和年龄 姓名和位置 年龄和位置 当我尝
  • 在 Android 中使用意图分享到 Facebook

    我使用以下代码来分享内容 Intent intent new Intent Intent ACTION SEND intent setType text plain intent putExtra Intent EXTRA TEXT The
  • Firebase Firestore:orderBy 与 where 结合导致错误“操作被拒绝”

    我正在查看 Firebase Cloud Firestore文档对于 orderBy 当我尝试执行这个时 var facultyQuery facultyRef where department Core Teacher orderBy b
  • 具有整数参数的模板的部分特化

    我正在尝试做一些部分专业化的事情 我有一个tuple 我想从某个元素索引迭代到第一个元组索引 累积每个类型的值tuple 这似乎是使用递归模板实例化的简单问题 问题是 我似乎无法让递归工作 为了停止递归 我需要部分特化元组索引 0 处的模板
  • softmax函数的导数解释[关闭]

    Closed 这个问题不符合堆栈溢出指南 目前不接受答案 我正在尝试计算 softmax 激活函数的导数 我找到了这个 https math stackexchange com questions 945871 derivative of
  • 写入文件时插入换行符吗?

    所以我的代码如下所示 try while line br readLine null Matcher m urlPattern matcher line while m find System out println m group 1 t
  • R 返回行名称的部分匹配

    我遇到了以下问题 vec lt c a11 b21 c31 df lt data frame a c 0 0 0 b c 1 1 1 row names vec df a returns df a a b a11 0 1 However a
  • 类型变量不明确但在 ghci 中没有?

    任何人都可以解释为什么 haskell 在下面的示例中强制执行显式类型签名以及如何修改它以避免需要显式声明 import qualified Data List as L main do print length L nub 1 1 2 3
  • 错误:不兼容的字符编码:UTF-8 和 ASCII-8BIT

    我收到错误incompatible character encodings UTF 8 and ASCII 8BIT 当视图在数据库中发现一些字符 如 等 我的环境是 轨道 3 2 5 红宝石 1 9 4p194 数据库 Oracle 10
  • java中如何比较时间字符串和当前时间?

    我有一个像 15 30 这样的时间字符串 我想将该字符串与当前时间进行比较 请建议一些简单的事情 以及如何以小时分钟格式获取当前时间 HH mm tl dr LocalTime now isAfter LocalTime parse 15
  • Python - 如何检测用户何时通过“X”按钮关闭控制台应用程序

    I currently have a Console based python program running under windows The program maintains most of its data in memory a
  • 使用 React 切换 Font Awesome 5 图标

    我试图通过单击待办事项列表项来切换 Font Awesome 图标 这是整个组件 import React from react import TodoItem scss class TodoItem extends React Compo
  • 如何检查图像质量/分辨率/dpi/ppi? [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 我想检查所选输入图像文件的当前质量 分辨率 dpi ppi 我的控件是图像上传器 jquery 插件 如何获得所选文件的质量 我需要所选图像文件的分辨率而不是屏幕分辨率 Note
  • 如何在 iPhone SDK 中向 Core Plot 添加图例?

    如何在 Core Plot 框架中添加图例 我非常感谢任何指导或帮助 更新 CorePlot 0 4 具有 CPTLegend 类 graph legend CPTLegend legendWithGraph graph graph leg
  • 在 VB.NET 中使用 Web 服务

    我第一次在 NET 中测试 Web 服务 我快到了 但我似乎无法使用网络服务 我知道这篇文章与该网站上的其他 5 6 篇文章类似 但我已经审阅了它们 但仍然无法获得正确的语法 到目前为止 我有 创建一个简单的 Web 服务来创建目录 在开发
  • 如何使用 JavaScript 以编程方式设置 input:focus 样式

    我正在 JS 中构建一个 UI 库 它可以在不依赖任何 CSS 样式表的情况下创建通过代码进行风格化的 UI 组件 到目前为止 除了设置不同控件状态的样式 例如输入 焦点之一 之外 一切都非常简单 我用来创建输入字段的代码 function
  • 如何减少 pandas DataFrame 的内存?

    我在日常工作中使用 pandas 并且我使用的一些数据框非常大 大约数亿行乘以数百列 有什么方法可以减少 RAM 内存消耗吗 您可以使用此功能 它通过将数据类型限制为每列所需的最小值来减少数据的大小 该代码不是我的 我从以下链接复制了它 并