pandas 读取数据时优化内存

当 pandas 读取超过100M数据时需要优化内存,将数据转换为合理的数据类型。

  • 程序
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
    to reduce memory usage.
"""   
    start_mem = df.memory_usage().sum() / 1024 ** 2
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
    for col in df.columns:
        col_type = df[col].dtype

        if col_type != object:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == '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.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                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.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)
            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)
        else:
            df[col] = df[col].astype('category')

    end_mem = df.memory_usage().sum() / 1024 ** 2
    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))

    return df

def import_data(file):
    """create a dataframe and optimize its memory usage"""
    df = pd.read_csv(file, parse_dates=True, keep_date_col=True)
    df = reduce_mem_usage(df)
    return df
  • 实例,数据集大小300多M
file_name = 'nyc_taxi_data.csv'
data = import_data(file_name)

运行结果:

从运行结果可以看出内存使用率从407M下降到了91M,下降了77.5%,大大提高了效率

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在上一篇文章中,说到,使用python3.5版是可以轻轻松松把pyspider安装上的,那本篇证实python3....
    starrymusic阅读 2,472评论 0 0
  • 1、虎式热身 2、卧推测试 6kg,10个,1分钟休息 11kg,5个,1分钟休息 16kg,5个,1分钟休息 2...
    JanePlus阅读 1,189评论 0 0
  • 2017.5.16——2017.5.18 时至今日,人类已经进入了【造假】(artificial)的大门,这...
    hoing阅读 3,021评论 3 3
  • 2018.9.7 17:30 一. 最高人民法院:法院应对通过区块链等技术收集的证据予以...
    三角形T阅读 1,430评论 0 0