gpt4 book ai didi

python - 关于pandas copy()方法的查询

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:30 25 4
gpt4 key购买 nike

df1 = pd.DataFrame({'A':['aaa','bbb','ccc'], 'B':[1,2,3]})
df2=df1.copy()
df1.loc[0,'A']='111' #modifying the 1st element of column A
print df1
print df2

当修改 df1 时,对象 sf2 不会被修改。我预料到了,因为我使用了 copy()

s1=pd.Series([[1,2],[3,4]])
s2=s1.copy()
s1[0][0]=0 #modifying the 1st element of list [1,2]
print s1
print s2

但为什么 s2 在这种情况下也发生了变化?我预计 s2 没有变化,因为我使用 copy() 来创建它,但令我惊讶的是,在修改 s1 对象时 s2 也被修改。我不明白为什么。

最佳答案

这是因为您的 pd.Series 是 dtype=object,所以它实际上复制了一堆对 python 对象的引用。观察:

In [1]: import pandas as pd

In [2]: s1=pd.Series([[1,2],[3,4]])
...:

In [3]: s1
Out[3]:
0 [1, 2]
1 [3, 4]
dtype: object

In [4]: s1.dtype
Out[4]: dtype('O')

由于 list 对象是可变的,那么操作:

s1[0][0]=0

就地修改列表。

这种行为是“浅拷贝”,通常对于 pandas 数据结构来说不是问题,因为通常您会使用数字数据类型,其中如果浅拷贝不适用,或者如果您确实使用了对象数据类型,您将使用不可变的 python 字符串对象。

请注意,pandas 容器具有不同的深层复制概念。请注意 .copy 方法有一个默认的 deep=True,但是从文档中可以看出:

When deep=True (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below).

When deep=False, a new object will be created without copying the calling object's data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa). ... When deep=True, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below).

同样,这是因为 pandas 是为使用数字数据类型而设计的,并且对 str 对象有一些内置支持。 list 对象的 pd.Series 确实很奇怪,而且对于 pd.Series 来说真的不是一个好的用例。

关于python - 关于pandas copy()方法的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58546554/

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