Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make a truly deep copy of a pandas Series

I have a pd.Series with each cell being a list. I want to make a deep copy of it, however it seems like pd.Series.copy only creates a shallow copy of the values (even though the deep arg is True be default).

example

import pandas as pd

sr = pd.Series([list(range(3)), list(range(3))])
sr_c = sr.copy()
sr[0].append(4)

the copied pd.Series sr_c is being transformed to

0   [0, 1, 2, 4]
1   [0, 1, 2]

I did this and it worked:

from copy import deepcopy
sr_c = sr_c.apply(deepcopy)

however this seems like a hack, is there a better way to do it ?

like image 951
moshevi Avatar asked Oct 08 '18 18:10

moshevi


People also ask

How do you make a deep copy in pandas?

To create deep copy of Pandas DataFrame, use df. copy() or df. copy(deep=True) method.

How do you create a copy of a given series in pandas?

Pandas DataFrame copy() Method The copy() method returns a copy of the DataFrame. By default, the copy is a "deep copy" meaning that any changes made in the original DataFrame will NOT be reflected in the copy.

How do you copy a series in Python?

Example: Set deep=False in the Series. copy() Method set to True. Here, in this example, we set the parameter deep=True in the Series. copy() Method. Now, this method copies the Series object with indices and data, but if we make any changes to the Series, it will reflect the original Series also.

How do you make a deep copy in Python?

To make a deep copy, use the deepcopy() function of the copy module. In a deep copy, copies are inserted instead of references to objects, so changing one does not change the other.


1 Answers

The standard hacky way of deep-copying python objects should work. That is, using pickle.

import pickle
sr2 = pickle.loads(pickle.dumps(sr))
like image 70
shx2 Avatar answered Sep 29 '22 01:09

shx2