guidelines on using pandas inplace keyword argument

一世执手 提交于 2019-12-18 16:46:43

问题


What is the guideline for using inplace?

For example,

df = df.reset_index()

or

df.reset_index(inplace=True)

Same same but different?


回答1:


In terms of the resulting DataFrame df, the two approaches are the same. The difference lies in the (maximum) memory usage, since the in-place version does not create a copy of the DataFrame.

Consider this setup:

import numpy as np
import pandas as pd

def make_data():
    return pd.DataFrame(np.random.rand(1000000, 100))

def func_copy():
    df = make_data()
    df = df.reset_index()

def func_inplace():
    df = make_data()
    df.reset_index(inplace=True)

We can use the memory_profile library to perform some benchmarking for the memory usage:

%load_ext memory_profiler

%memit func_copy()
# peak memory: 1602.66 MiB, increment: 1548.66 MiB

%memit func_inplace()
# peak memory: 817.02 MiB, increment: 762.94 MiB

As expected, the in-place version is more memory efficient.

On the other hand, there also seems to be a non-trivial difference in running time between the approaches when the data size is large enough (e.g. in the above example):

%timeit func_copy()
1 loops, best of 3: 2.56 s per loop

%timeit func_inplace()
1 loops, best of 3: 1.35 s per loop

These differences may or may not be significant depending on the use case (e.g. adhoc exploratory analysis vs. production code), data size and the hardware resource available. In general, it might be a good idea to use the in-place version whenever possible for better memory and run time efficiency.



来源:https://stackoverflow.com/questions/34320137/guidelines-on-using-pandas-inplace-keyword-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!