压缩pandas中dataframe内存

从这里找的一个宝贝源码,可以大大缓解内存问题。https://www.kaggle.com/arjanso/reducing-dataframe-memory-size-by-65/code

# @from: https://www.kaggle.com/arjanso/reducing-dataframe-memory-size-by-65/code
# @liscense: Apache 2.0
# @author: weijian
def reduce_mem_usage(props):
    # 计算当前内存
    start_mem_usg = props.memory_usage().sum() / 1024 ** 2
    print("Memory usage of the dataframe is :", start_mem_usg, "MB")

    # 哪些列包含空值,空值用-999填充。why:因为np.nan当做float处理
    NAlist = []
    for col in props.columns:
        # 这里只过滤了objectd格式,如果你的代码中还包含其他类型,请一并过滤
        if (props[col].dtypes != object):

            print("**************************")
            print("columns: ", col)
            print("dtype before", props[col].dtype)

            # 判断是否是int类型
            isInt = False
            mmax = props[col].max()
            mmin = props[col].min()

            # Integer does not support NA, therefore Na needs to be filled
            if not np.isfinite(props[col]).all():
                NAlist.append(col)
                props[col].fillna(-999, inplace=True) # 用-999填充

            # test if column can be converted to an integer
            asint = props[col].fillna(0).astype(np.int64)
            result = np.fabs(props[col] - asint)
            result = result.sum()
            if result < 0.01: # 绝对误差和小于0.01认为可以转换的,要根据task修改
                isInt = True

            # make interger / unsigned Integer datatypes
            if isInt:
                if mmin >= 0: # 最小值大于0,转换成无符号整型
                    if mmax <= 255:
                        props[col] = props[col].astype(np.uint8)
                    elif mmax <= 65535:
                        props[col] = props[col].astype(np.uint16)
                    elif mmax <= 4294967295:
                        props[col] = props[col].astype(np.uint32)
                    else:
                        props[col] = props[col].astype(np.uint64)
                else: # 转换成有符号整型
                    if mmin > np.iinfo(np.int8).min and mmax < np.iinfo(np.int8).max:
                        props[col] = props[col].astype(np.int8)
                    elif mmin > np.iinfo(np.int16).min and mmax < np.iinfo(np.int16).max:
                        props[col] = props[col].astype(np.int16)
                    elif mmin > np.iinfo(np.int32).min and mmax < np.iinfo(np.int32).max:
                        props[col] = props[col].astype(np.int32)
                    elif mmin > np.iinfo(np.int64).min and mmax < np.iinfo(np.int64).max:
                        props[col] = props[col].astype(np.int64)
            else: # 注意:这里对于float都转换成float16,需要根据你的情况自己更改
                props[col] = props[col].astype(np.float16)

            print("dtype after", props[col].dtype)
            print("********************************")
    print("___MEMORY USAGE AFTER COMPLETION:___")
    mem_usg = props.memory_usage().sum() / 1024**2
    print("Memory usage is: ",mem_usg," MB")
    print("This is ",100*mem_usg/start_mem_usg,"% of the initial size")
    return props, NAlist

原文地址:https://www.cnblogs.com/duoba/p/12431544.html

时间: 2024-08-01 07:15:23

压缩pandas中dataframe内存的相关文章

pandas中DataFrame

python数据分析工具pandas中DataFrame和Series作为主要的数据结构. 本文主要是介绍如何对DataFrame数据进行操作并结合一个实例测试操作函数. 1)查看DataFrame数据及属性 df_obj = DataFrame() #创建DataFrame对象 df_obj.dtypes #查看各行的数据格式 df_obj['列名'].astype(int)#转换某列的数据类型 df_obj.head() #查看前几行的数据,默认前5行 df_obj.tail() #查看后几

Pandas中DataFrame数据合并、连接(concat、merge、join)之merge

二.merge:通过键拼接列 类似于关系型数据库的连接方式,可以根据一个或多个键将不同的DatFrame连接起来. 该函数的典型应用场景是,针对同一个主键存在两张不同字段的表,根据主键整合到一张表里面. merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixes=('_x', '_y'), copy=Tr

pandas中DataFrame类的pivot_table函数------Reshaping by pivoting DataFrame objects

以下内容为截取自pandas官网的doc(请看这里),我做了一些翻译. Reshaping by pivoting DataFrame objects Data is often stored in CSV files or databases in so-called “stacked” or “record” format: In [1]: df Out[1]: date variable value 0 2000-01-03 A 0.469112 1 2000-01-04 A -0.282

pandas中DataFrame相关

1.创建 1.1  标准格式创建 DataFrame创建方法有很多,常用基本格式是:DataFrame 构造器参数:DataFrame(data=[],index=[],coloumns=[]) In [272]: df2=DataFrame(np.arange(16).reshape((4,4)),index=['a','b','c','d'],columns=['one','two','three','four']) In [273]: df2 Out[273]: one two three

pandas中DataFrame逐行读取的方法

1 2 3 4 5 6 import pandas as pd dict=[[1,2,3,4,5,6],[2,3,4,5,6,7],[3,4,5,6,7,8],[4,5,6,7,8,9],[5,6,7,8,9,10]] data=pd.DataFrame(dict) print(data) for indexs in data.index: print(data.loc[indexs].values[0:-1]) 实验结果: 0 1 2 3 4 5 0 1 2 3 4 5 6 1 2 3 4 5

Pandas中DataFrame数据合并、连接(concat、merge、join)之concat

一.concat:沿着一条轴,将多个对象堆叠到一起 concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True): objs:需要连接的对象集合,一般是列表或字典: axis:连接轴向: join:参数为'outer'或'inner': join_axes=[]:指定自定义的索

Pandas中DataFrame数据合并、连接(concat、merge、join)之join

pandas.DataFrame.join 自己弄了很久,一看官网.感觉自己宛如智障.不要脸了,直接抄 DataFrame.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by in

解决问题:使用pandas中DataFrame如何使用条件选择某行

初始化 data = {'db':['my','my','my','dm','dm','dm'],'table':['s','cs','c','book','order','cus']} >>> data = DataFrame(data) >>> data db table 0 my s 1 my cs 2 my c 3 dm book 4 dm order 5 dm cus 如果我想选择出‘db’ == ‘my’ 的所有行,操作如下: data.loc[data['

pandas中选取某行为缺失值的数据,并返回

1.df.dropna() 可以返回去掉NaN的df结果集. 2.pandas中dataframe取差集: df=pd.DataFrame({"name":[1,2,3,np.NaN,8],"value":[3,4,np.NaN,9,0]}) drop_na_df=df.dropna() na_symbols_df=pd.DataFrame(list(set(df["name"])^set(drop_na_df["name"]