Question

I use pandas version 0.12.0. and the following code which shifts the index of a copied series:

import pandas as pd
series = pd.Series(range(3))
series_copy = series.copy()
series_copy.index += 1

If I now access series it also has the index shifted. Why?

Was it helpful?

Solution

copy is defined as a helper to do a copy of the underlying arrays, and the function does not copy the index. See the source code:

Definition: series.copy(self, order='C')
Source:
    def copy(self, order='C'):
        """
        Return new Series with copy of underlying values

        Returns
        -------
        cp : Series
        """
        return Series(self.values.copy(order), index=self.index,
                      name=self.name)

The index remains shared by construction. If you want a deeper copy, then just use directly the Series constructor:

series = pd.Series(range(3))
    ...: series_copy = pd.Series(series.values.copy(), index=series.index.copy(),
    ...:                           name=series.name)
    ...: series_copy.index += 1

series
Out[72]: 
0    0
1    1
2    2
dtype: int64

series_copy
Out[73]: 
1    0
2    1
3    2
dtype: int64

In 0.13, copy(deep=True) is the default interface for copy that will solve your issue. (Fix is here)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top