创建df复制:
1.直接用df2=df1,修改df2会对df1造成影响:
In [21]: import pandas as pd
In [22]: data = {'a':[1,2,3],'b':[4,5,6]}
...: df1=pd.DataFrame(data)
...: df1
Out[22]:
a b
0 1 4
1 2 5
2 3 6
In [23]: df2=df1
In [24]: df2['a']=0
In [25]: df2
Out[25]:
a b
0 0 4
1 0 5
2 0 6
In [27]: df1
Out[27]:
a b
0 0 4
1 0 5
2 0 6
2.想要修改复制后的df3而不改变df1用copy()函数:
In [28]: data = {'a':[1,2,3],'b':[4,5,6]}
In [29]: df1=pd.DataFrame(data)
In [30]: df1
Out[30]:
a b
0 1 4
1 2 5
2 3 6
In [31]: df3=df1.copy()
In [32]: df3
Out[32]:
a b
0 1 4
1 2 5
2 3 6
In [33]: df3['a']=0
In [34]: df3
Out[34]:
a b
0 0 4
1 0 5
2 0 6
In [35]: df1
Out[35]:
a b
0 1 4
1 2 5
2 3 6