Why are attributes lost after copying a Pandas DataFrame

前端 未结 4 1533
野的像风
野的像风 2021-02-19 02:07

Why is it not possible to pass attributes of an instance through a copy? I want to pass the name attribute to another dataframe.

import copy
df = pd         


        
4条回答
  •  借酒劲吻你
    2021-02-19 02:29

    The copy.deepcopy will use a custom __deepcopy__ method if it is found in the MRO, which may return whatever it likes (including completely bogus results). Indeed dataframes implement a __deepcopy__ method:

    def __deepcopy__(self, memo=None):
        if memo is None:
            memo = {}
        return self.copy(deep=True)
    

    It delegates to self.copy, where you will find this note in the docstring:

    Notes
    -----
    When ``deep=True``, data is copied but actual Python objects
    will not be copied recursively, only the reference to the object.
    This is in contrast to `copy.deepcopy` in the Standard Library,
    which recursively copies object data (see examples below).
    

    And you will find in the v0.13 release notes (merged in PR 4039):

    __deepcopy__ now returns a shallow copy (currently: a view) of the data - allowing metadata changes.

    Related issue: 17406.

提交回复
热议问题