Pandas的View和Copy

View vs Copy

記一下這兩天發現的問題.python

對frame或者series進行操做常常不知道會不會對原數據操做改變,並且與遇到SetingWithView的警告,作了下實驗。測試

Series

太長不看:code

  1. slice是view (和numpy保持一致)
  2. loc進行boolean篩選後的新Series是copy
  3. copy()方法後的是copy
  4. Series.T 轉置以後的Series也是view (和numpy保持一致)

DataFrame

太長不看:pandas

  1. 對index或者column 進行slice是view
  2. loc單選一個index 或一個column是view
  3. loc進行boolean篩選是copy
  4. loc進行[ ] or () 選擇是copy
  5. 使用1.2.3.4對frame同時進行index和column的操做,當且僅當index和column都是結果爲view操做時,返回的frame或series纔是view,其餘是copy

詳細

太忙了,下次再寫it

測試code

import numpy as np
import pandas as pd

a=pd.Series([1,2,3,4,5,6,7,8,9])
aid(a.values),aid(a.copy().values),aid(a[0:2].values),aid(a.loc[a%2==0].values),aid(a.T.values)

A=pd.DataFrame([[0,0,0],[0,0,0],[0,0,0]],columns=['c1','c2','c3'])
B=A['c1']
C=A.loc[:,'c1']
C1=A.loc[:,['c1']]
# D=A.loc[:,'c1':'c2']
E=A.T
aid(A['c1'].values),aid(B.values),aid(C.values),aid(C1['c1'].values),aid(E.loc[].values) #,aid(D['c1'].values)

# another testing
A=pd.DataFrame([[0,0,0],[0,0,0],[0,0,0]],columns=['c1','c2','c3'])


B=A.loc[0]
C=A.loc[0:1]
C1=A.loc[0:1,['c1','c2']]
C2=A.loc[0:1,'c1']
D=A.loc[A.index<2]


A.at[0,'c1']=1

print('A......')
print(A)
print('B......')
print(B)
print('C......')
print(C)
print('C1......')
print(C1)
print('C2......')
print(C2)
print('D......')
print(D)
相關文章
相關標籤/搜索