Python Pandas – DataFrame.copy()函数
Python是一种很好的数据分析语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas 就是其中之一,它使导入和分析数据变得更加容易。
在 Pandas 中有很多方法可以复制 DataFrame。第一种方法是将数据帧对象分配给变量的简单方法,但这有一些缺点。
Syntax: DataFrame.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).
步骤1)让我们首先制作一个虚拟数据框,用于我们的说明
步骤2)将该数据帧对象分配给一个变量
步骤 3)在原始数据框中进行更改以查看复制的变量是否有任何差异
Python3
import pandas as pd
#Create Series
s = pd.Series([3,4,5],['earth','mars','jupiter'])
k = pd.Series([1,2,3],['earth','mars','jupiter'])
#Create DataFrame df from two series
df = pd.DataFrame({'mass':s,'diameter':k})
df
Python3
#Assign df to variable_copy
variable_copy = df
print(variable_copy)
#Update the value of mass of earth in original dataframe
df['mass']['earth']=8
print(variable_copy)
Python3
res = df.copy(deep=True)
print(res)
输出:
现在,让我们将数据帧 df 分配给一个变量并执行更改:
蟒蛇3
#Assign df to variable_copy
variable_copy = df
print(variable_copy)
#Update the value of mass of earth in original dataframe
df['mass']['earth']=8
print(variable_copy)
输出:
在这里,我们可以看到,如果我们更改原始数据帧中的值,那么复制的变量中的数据也会发生变化。为了克服这个,我们使用 DataFrame.copy()
让我们看看这个,当 deep=True(default) 时的例子:
蟒蛇3
res = df.copy(deep=True)
print(res)
输出: