You are currently viewing Efficiently Manage Memory Usage in Pandas with Large Datasets

Efficiently Manage Memory Usage in Pandas with Large Datasets

Pandas supports Copy-on-Write, an optimization technique that helps improve memory use, particularly when working with large datasets.

Starting from version 2.0 of Pandas, the Copy-on-Write (CoW) has taken effect but has not been fully implemented. Most of the optimizations that are possible through Copy-on-Write are supported.

Aim of Copy-on-Write

As the name suggests, the data will be copied when it is modified. What it means?

When a DataFrame or Series shares the same data as the original, it will initially share the same memory for the data rather than creating a copy. When the data of either the original or new DataFrame is modified, a new copy of the data is created for the DataFrame that is being modified.

This will efficiently save memory usage and improve performance when working with large datasets.

Enabling CoW in Pandas

It is not enabled by default, so we need to enable it using the copy_on_write configuration option in Pandas.

You can use any of the options to turn on CoW globally in your environment.

Note: CoW will be enabled by default in Pandas 3.0, so get used to it early on.

Impact of CoW in Pandas

The CoW will disallow updating the multiple pandas objects at the same time. Here’s how it will happen.

With CoW, the above snippet will not modify df rather it modifies only the data of subset.

inplace Operations will Not Work

Similarly, the inplace operations will not work with CoW enabled, which directly modifies the original df.

We can see that df has remained unchanged and additionally, we will see a ChainedAssignmentError warning.

The above operation can be performed in two different ways. One method is to avoid inplace, and another is to use inplace to directly modify the original df at the DataFrame level.

Chained Assignment will Never Work

When we modify the DataFrame or Series using multiple indexing operations in a single line of code, this is what we call the chained assignment technique.

The above code snippet is trying to change column B from the original df where column A is greater than 2. It means the value at the 2nd and 3rd index in column B will be modified.

Since the CoW is disabled, this operation is allowed, and the original df will be modified.

But, this will never work with CoW enabled in pandas.

Instead, with copy-on-write, we can use .loc to modify the df using multiple indexing conditions.

This will modify column B where column A is either 1 or greater than 3. The original df will look like the following.

Read-only Arrays

When a Series or DataFrame is accessed as a NumPy array, that array will be read-only if the array shares the same data with the initial DataFrame or Series.

In the above code snippet, arr will be a copy because df contains two different types of arrays (int and str). We can perform modifications on the arr.

Take a look at this case.

The DataFrame df has only one NumPy array (array of the same data types), so arr shares the data with df. This means arr will be read-only and cannot be modified in place.

Lazy Copy Mechanism

When two or more DataFrames share the same data, the copies will not be created immediately.

Both df and df2 shares the same reference in the memory as both share the same data. The copy mechanism will trigger only when any of the DataFrame is modified.

But this is not necessary, if we don’t want initial df, we can simply reassign it to the same variable (df) and this process will create a new reference. This will avoid the copy-on-write process.

This same optimization (lazy copy mechanism) is added to the methods that don’t require a copy of the original data.

DataFrame.rename()

When CoW is enabled, this method returns the original DataFrame rather than creating an entire copy of the data, unlike the regular execution.

DataFrame.drop() for axis=1

Similarly, the same mechanism is implemented for DataFrame.drop() for axis=1 (axis='columns').

Conclusion

Pandas will by default implement Copy-on-Write (CoW) in version 3.0. All these optimizations that are compliant with CoW will lead to efficient memory and resource management when working with large datasets.

This will reduce unpredictable or inconsistent behavior and greatly maximize performance.


πŸ†Other articles you might be interested in if you liked this one

βœ…Merge, combine, and concatenate multiple datasets using pandas.

βœ…Find and delete duplicate rows from the dataset using pandas.

βœ…Find and Delete Mismatched Columns From DataFrames Using pandas.

βœ…Create temporary files and directories using tempfile module in Python.

βœ…Upload and display images on the frontend using Flask.

βœ…How does the learning rate affect the ML and DL models?


That’s all for now

Keep Coding✌✌