1. 程式人生 > >pandas 學習彙總8 - Series系列,DataFrame資料幀新增刪除(行列)( tcy)

pandas 學習彙總8 - Series系列,DataFrame資料幀新增刪除(行列)( tcy)

新增刪除 2018/12/3

1.函式:

s1.append(to_append, ignore_index=False, verify_integrity=False)       #更多序列連線
df.append(other, ignore_index=False, verify_integrity=False, sort=None)#資料幀連線

s1.drop(labels=None)                                                   #刪除系列指定的標籤
df.drop(labels=None, axis=0, index=None, columns=None, level=None)     #資料幀刪除
# 注:操作後原資料不變
2.例項

1.1).Series新增
s1=pd.Series([-1, -2, -3], index=['a', 'b', 'c'])
s2=pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
s1['d']=-4                         #系列新增; 原資料改變

# 序列連線
s1.append(s2)                      #s2必須是系列,保留原資料標籤
s1.append(s2,ignore_index=True)    #忽略原資料標籤,啟用新的標籤0,1,2,
s1.append(s2,verify_integrity=True)#標籤重複報錯 

1.2).Series 刪除  

del s1['d'] #序列刪除;原資料改變
# del s1.d  #錯誤用法
s2.pop('d') #彈出;引數必須為標籤str;原資料改變

s2.drop('d')       #刪除資料‘d' ; 原資料不變
s2.drop(['c','d']) #刪除資料‘'c',d'
2.1).DataFrame新增
s1=pd.Series([-1, -2, -3], index=['a', 'b', 'c'])
s2=pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
df = pd.DataFrame({'one' : s1,'two' : s2})
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=['one','two'])

#新增列
df['three']=pd.Series([10,20,30],index=['a','b','c'])#資料幀新增1列;原資料改變
df['four']=df['one']+df['three']                     #資料幀新增1列;原資料改變

# 新增行
df.append(df2)                                       #新增2行,保留原資料標籤 ; 原資料不變
2.2).DataFrame刪除
#刪除列
del df['four'] #資料幀刪除;原資料改變
# del df.four  #錯誤用法
df.pop('three')#彈出;引數必須為標籤str;原資料改變

df.drop(['one'],axis=1)#刪除列; 原資料不變
# two
# a 1
# b 2
# c 3
# d 4

#刪除行
df.drop(['a','b'])#通過索引刪除行; 原資料不變
# one two
# c -3.0 3
# d NaN 4
3.備註-多索引
Drop columns and/or rows of MultiIndex DataFrame
midx = pd.MultiIndex(levels=[['Tom', 'Bob', 'Jam'], ['income', 'weight', 'length']],
labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2],[0, 1, 2, 0, 1, 2, 0, 1, 2]])#建立多索引
df = pd.DataFrame(index=midx, columns=['max', 'min'],
data=[[200, 100],[55, 50], [1.5, 1.4], #Tom收入,體重,身高
      [400, 300],[65, 60], [1.6, 1.5], # Bob收入,體重,身高
      [600, 500],[75, 70], [1.8, 1.7]])# Jam收入,體重,身高
df'''
           max min
Tom income 200.0 100.0
    weight 55.0 50.0
    length 1.5 1.4
Bob income 400.0 300.0
    weight 65.0 60.0
    length 1.6 1.5
Jam income 600.0 500.0
    weight 75.0 70.0
    length 1.8 1.7
'''
df.drop(index='Bob', columns='min')
'''''''''''
           max
Tom income 200.0
    weight 55.0
    length 1.5
Jam income 600.0
    weight 75.0
    length 1.8
'''
df.drop(index='length', level=1)
'''''''''
             max min
Tom income 200.0 100.0
    weight 55.0 50.0
Bob income 400.0 300.0
    weight 65.0 60.0
Jam income 600.0 500.0
    weight 75.0 70.0
'''