Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas.series.copy doesn't create new object

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?

like image 656
Joerg Avatar asked Nov 14 '13 10:11

Joerg


People also ask

How do I copy a series in pandas?

copy() method is used to create a copy of a series object's indices and its data (values). And it returns a copied series object as a result. The copy() method has one parameter which is “deep”. The default value for this deep parameter is True.

What does Copy () do in python 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.

Does ILOC work on series?

iloc attribute enables purely integer-location based indexing for selection by position over the given Series object. Example #1: Use Series. iloc attribute to perform indexing over the given Series object.

How do you repeat a panda series?

Pandas Series: repeat() function The repeat() function is used to repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a given number of times. The number of repetitions for each element. This should be a non-negative integer.


1 Answers

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)

like image 152
Zeugma Avatar answered Nov 03 '22 20:11

Zeugma