你的答案在于熊猫文档:returning-a-view-versus-a-copy。
每当标签的阵列或一个布尔矢量参与转位操作 ,的结果将是一个拷贝。使用单标签/标量索引和切片,例如 df.ix [3:6]或df.ix [:,'A'],将返回视图。
在您的例子,bar
是foo
切片的视图。如果你想要一个拷贝,你可以使用copy
方法。修改bar
也会修改foo
。熊猫似乎没有写入时复制机制。
见下面我的代码的例子来说明:
In [1]: import pandas as pd
...: import numpy as np
...: foo = pd.DataFrame(np.random.random((10,5)))
...:
In [2]: pd.__version__
Out[2]: '0.12.0.dev-35312e4'
In [3]: np.__version__
Out[3]: '1.7.1'
In [4]: # DataFrame has copy method
...: foo_copy = foo.copy()
In [5]: bar = foo.iloc[3:5,1:4]
In [6]: bar == foo.iloc[3:5,1:4] == foo_copy.iloc[3:5,1:4]
Out[6]:
1 2 3
3 True True True
4 True True True
In [7]: # Changing the view
...: bar.ix[3,1] = 5
In [8]: # View and DataFrame still equal
...: bar == foo.iloc[3:5,1:4]
Out[8]:
1 2 3
3 True True True
4 True True True
In [9]: # It is now different from a copy of original
...: bar == foo_copy.iloc[3:5,1:4]
Out[9]:
1 2 3
3 False True True
4 True True True
所以当我做bar.loc [:, [ '一', 'B']返回一个拷贝,但是当我做bar.loc [:,'a']它返回一个视图? – Lisa