Skip to content Skip to sidebar Skip to footer

Guidelines On Using Pandas Inplace Keyword Argument

What is the guideline for using inplace? For example, df = df.reset_index() or df.reset_index(inplace=True) Same same but different?

Solution 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

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

deffunc_copy():
    df = make_data()
    df = df.reset_index()
    
deffunc_inplace():
    df = make_data()
    df.reset_index(inplace=True)

We can use the memory_profiler 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.

Post a Comment for "Guidelines On Using Pandas Inplace Keyword Argument"