Pandas 系列中的浅拷贝与深拷贝
pandas 库主要有 DataFrames 和 Series 两种数据结构。这些数据结构在内部用索引数组表示,索引数组标记数据,数据数组包含实际数据。现在,当我们尝试复制这些数据结构(DataFrames 和 Series)时,我们基本上复制了对象的索引和数据,有两种方法可以做到,即浅复制和深复制。
这些操作是在库函数pandas.Series.copy(deep=False)的帮助下完成的,用于浅拷贝, pandas.Series.copy(deep=True)用于深拷贝。
现在,让我们了解什么是浅拷贝。
浅拷贝
创建 Series 或 Series 对象的浅表副本时,它不会复制原始对象的索引和数据,而只是复制对其索引和数据的引用。因此,对一个所做的更改会反映在另一个中。
它指的是构造一个新的集合对象,然后使用对原始集合中找到的子对象的引用来填充它。复制过程不会递归,因此不会创建子对象本身的副本。
例子:
Python3
# program to depict shallow copy
# in pandas series
# import module
import pandas as pd
# assign series
ser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek'])
# shallow copy
copyser = ser.copy(deep=False)
# comparing shallow copied series
# and original series
print('\nBefore Operation:\n', copyser == ser)
# assignment operation
copyser[2] = 'Geeks'
# comparing shallow copied series
# and original series
print('\nAfter Operation:\n', copyser == ser)
print('\nOriginal Dataframe after operation:\n', ser)
Python3
# program to depict deep copy
# in pandas series
# import module
import pandas as pd
# assign series
ser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek'])
# shallow copy
copyser = ser.copy(deep=True)
# comparing deep copied series
# and original series
print('\nBefore Operation:\n', copyser == ser)
# assignment operation
copyser[2] = 'Geeks'
# comparing deep copied series
# and original series
print('\nAfter Operation:\n', copyser == ser)
print('\nOriginal Dataframe after operation:\n', ser)
输出:
从上述程序的输出中可以看出,应用于浅复制数据框的更改会自动应用于原始系列。
深拷贝
Series 或 Series 对象的深层副本具有自己的索引和数据副本。这是一个复制过程递归发生的过程。这意味着首先构造一个新的集合对象,然后用在原始对象中找到的子对象的副本递归地填充它。在深拷贝的情况下,一个对象的副本被复制到另一个对象中。这意味着对对象副本所做的任何更改都不会反映在原始对象中。
例子:
蟒蛇3
# program to depict deep copy
# in pandas series
# import module
import pandas as pd
# assign series
ser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek'])
# shallow copy
copyser = ser.copy(deep=True)
# comparing deep copied series
# and original series
print('\nBefore Operation:\n', copyser == ser)
# assignment operation
copyser[2] = 'Geeks'
# comparing deep copied series
# and original series
print('\nAfter Operation:\n', copyser == ser)
print('\nOriginal Dataframe after operation:\n', ser)
输出:
在这里,原始对象内部的数据不会被递归复制。即原始对象的数据里面的数据仍然指向同一个内存单元。例如,如果 Series 对象中的数据包含任何可变数据,那么它将在它和它的深层副本之间共享,并且对一个的任何修改都将反映在另一个中。
浅拷贝 V/S 深拷贝区别表
Sr no. | Shallow Copy | Deep Copy |
---|---|---|
1 | It is the copy of the collection structure, not the elements. | It is the copy of the collections with all the elements in the original collection duplicated. |
2 | Affects the initial series. | Does not affect the initial series. |
3 | Shallow copy doesn’t replicate child objects. | Deep copy replicates child objects recursively. |
4 | Creating a shallow copy is fast as compared to a deep copy. | Creating a deep copy is slow as compared to a shallow copy. |
5 | The copy is dependent on the original | The copy is not fully dependent on the original. |