pandas.series.copy不会创建新对象

Joe*_*erg 5 python series pandas

我使用pandas版本0.12.0.和以下代码移动复制系列的索引:

import pandas as pd
series = pd.Series(range(3))
series_copy = series.copy()
series_copy.index += 1
Run Code Online (Sandbox Code Playgroud)

如果我现在访问series它也会移动索引.为什么?

Bou*_*oud 5

copy被定义为执行底层数组副本的助手,该函数不会复制索引.查看源代码:

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)
Run Code Online (Sandbox Code Playgroud)

index遗骸的建设共享.如果你想要更深的副本,那么只需直接使用Series构造函数:

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
Run Code Online (Sandbox Code Playgroud)

在0.13中,copy(deep=True)是复制的默认界面,可以解决您的问题.(修复在这里)