你的答案在於熊貓文檔: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