Pandas DataFrame.copy(~)方法製作 DataFrame 的副本。您可以選擇是否想要深拷貝或一個淺拷貝.
A 深拷貝是一個全新的副本 - 修改 DataFrame 的深層副本不會改變原始 DataFrame,反之亦然。例外情況是當值是 Python 對象時;它們的屬性不是遞歸複製的,因此修改深層複製中的 Python 對象會改變原始對象,反之亦然.
A 淺拷貝與原始DataFrame 的數據共享相同的內存塊。這意味著如果您修改淺拷貝,則原始的 DataFrame 將發生變異,反之亦然。
參數
1.deep | boolean | optional
- 
如果 True,則執行深度複製。
- 
如果 False,則執行淺複製。
默認情況下,deep=True 。
返回值
DataFrame,它是源 DataFrame 的淺拷貝或深拷貝。
例子
深拷貝
考慮以下 DataFrame :
df = pd.DataFrame({"A":[1,2], "B":[3,4]})
df
   A  B
0  1  3
1  2  4我們執行深度複製來創建 df_other ,並將其第一個值更改為 5 :
df_other = df.copy()   # deep=True
df_other.iloc[0,0] = 5
df_other
   A  B
0  5  3
1  2  4然後我們檢查原始 DataFrame df 的狀態:
df
   A  B
0  1  3
1  2  4我們看到原來的DataFrame 完好無損。這是因為我們執行的是深複製,而不是淺複製。
例外
當 DataFrame 的值是 Python 對象時要小心 - 它們的屬性不會遞歸複製,因此在深層複製中修改它們仍然會改變原始 DataFrame 中的對象。
考慮以下 DataFrame :
df = pd.DataFrame({"A":[[1,2],3], "B":[4,5]})
df
   A       B
0  [1,2]   4
1  3       5我們製作 df 的新深層副本,並修改列表的第一個值:
df_other = df.copy(deep=True)
df_other.iloc[0,0][0] = 9      # Modify the first value in the Python list
df
   A       B
0  [9,2]   4
1  3       5我們可以看到 df_other 中的更改反映在原始 df 中。反之亦然,即修改 df 中的 Python 列表會改變 df_other 中的 Python 列表。
淺複製
考慮以下 DataFrame :
df = pd.DataFrame({"A":[1,2], "B":[3,4]})
df
   A  B
0  1  3
1  2  4我們執行淺複製來創建 df_other ,並將其第一個值更改為 5:
df_other = df.copy(deep=False)
df_other.iloc[0,0] = 5
df_other
   A  B
0  5  3
1  2  4然後我們檢查原始 DataFrame df 的狀態:
df
   A  B
0  5  3
1  2  4我們看到原來的DataFrame也被修改了,盡管我們從未直接修改過它。這是因為我們執行的是淺複製,而不是深複製。
此外,更改 df 也會修改 df_other :
df.iloc[0,0] = 6
df_other
   A  B
0  6  3
1  2  4相關用法
- Python PySpark DataFrame collect方法用法及代碼示例
- Python PySpark DataFrame coalesce方法用法及代碼示例
- Python Pandas DataFrame corrwith方法用法及代碼示例
- Python PySpark DataFrame corr方法用法及代碼示例
- Python Pandas DataFrame convert_dtypes方法用法及代碼示例
- Python Pandas DataFrame combine方法用法及代碼示例
- Python Pandas DataFrame columns屬性用法及代碼示例
- Python PySpark DataFrame cov方法用法及代碼示例
- Python Pandas DataFrame count方法用法及代碼示例
- Python PySpark DataFrame colRegex方法用法及代碼示例
- Python PySpark DataFrame columns屬性用法及代碼示例
- Python PySpark DataFrame count方法用法及代碼示例
- Python Pandas DataFrame corr方法用法及代碼示例
- Python Pandas DataFrame combine_first方法用法及代碼示例
- Python Pandas DataFrame cov方法用法及代碼示例
- Python Pandas DataFrame clip方法用法及代碼示例
- Python Pandas DataFrame cummax方法用法及代碼示例
- Python Pandas DataFrame cumprod方法用法及代碼示例
- Python Pandas DataFrame cummin方法用法及代碼示例
- Python Pandas DataFrame cumsum方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
- Python Pandas DataFrame items方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | copy method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
