make a truly deep copy of a pandas Series

蹲街弑〆低调 提交于 2020-06-14 07:28:03

问题


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 ?


回答1:


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

import pickle
sr2 = pickle.loads(pickle.dumps(sr))



回答2:


I have used

from copy import deepcopy
sr_copy = pd.Series( deepcopy(sr.to_dict()))

just to be sure that the index is copied recursively too (if needed).



来源:https://stackoverflow.com/questions/52708341/make-a-truly-deep-copy-of-a-pandas-series

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