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?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With