Pandas 中的 series.copy() 方法是如何工作的?
pandas.Series.copy() 方法用於建立系列物件索引及其資料(值)的副本。它返回一個複製的系列物件作為結果。
copy() 方法有一個引數“deep”。此 deep 引數的預設值為 True。當 deep 引數的輸入為“True”時,表示 copy 方法對給定的系列索引和資料也進行深複製。
如果 deep 引數的輸入為“False”,則表示 copy 方法建立一個物件,但不復制給定系列物件的資料和索引(它只複製資料和索引的引用)。
示例 1
import pandas as pd
index = list("WXYZ")
#create a pandas Series
series = pd.Series([98,23,43,45], index=index)
print(series)
# create a copy
copy_sr = series.copy()
print("Copied series object:",copy_sr)
# update a value
copy_sr['W'] = 55
print("objects after updating a value: ")
print(copy_sr)
print(series)解釋
最初,我們使用帶有標籤索引“W、X、Y、Z”的整數列表建立了一個 Pandas Series。之後使用 deep 引數的預設值(“True”)建立了一個複製的系列物件。
輸出
W 98 X 23 Y 43 Z 45 dtype: int64 Copied series object: W 98 X 23 Y 43 Z 45 dtype: int64 objects after updating a value: W 55 X 23 Y 43 Z 45 dtype: int64 W 98 X 23 Y 43 Z 45 dtype: int64
在上面的輸出塊中,我們可以看到初始系列物件和複製的物件。建立副本後,我們在複製的物件的索引位置“W”更新了一個值“55”。我們在複製的 Series 物件中所做的更改不會影響原始 Series。
示例 2
import pandas as pd
index = list("WXYZ")
#create a pandas Series
series = pd.Series([98,23,43,45], index=index)
print(series)
# create a copy
copy_sr = series.copy(deep=False)
print("Copied series object:",copy_sr)
copy_sr['W'] = 55
print("objects after updating a value: ")
print(copy_sr)
print(series)解釋
在此示例中,我們將 deep 引數的預設值從 True 更改為 False。因此,copy 方法使用索引和資料的引用 ID 複製 Series 物件。
如果我們對任何 Series 物件進行任何更改,這些更改也會反映在另一個 Series 物件上。
輸出
W 98 X 23 Y 43 Z 45 dtype: int64 Copied series object: W 98 X 23 Y 43 Z 45 dtype: int64 objects after updating a value: W 55 X 23 Y 43 Z 45 dtype: int64 W 55 X 23 Y 43 Z 45 dtype: int64
建立副本後。我們僅更新了複製系列中索引位置“W”處的值“55”,但更改也更新到了原始系列中。我們可以在上面的輸出塊中看到差異。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP