gpt4 book ai didi

python - pandas.series.copy 不创建新对象

转载 作者:太空狗 更新时间:2023-10-30 01:08:41 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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)

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

在 0.13 中,copy(deep=True) 是默认的复制接口(interface),可以解决您的问题。 ( Fix is here )

关于python - pandas.series.copy 不创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19975887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com