Pandas提供高性能的數據分析工具,此庫主要提供了兩個數據類型:Series和DataFrame(基於ndarray的數據類型)。
Pandas對象特徵:
相比於Numpy關注於數據的結構表達,Pandas更關注數據的應用表達,尤其是索引,通過對索引的改變,可以達到對數據改變的效果。
Series類型:
組成:Series類型由數據及其索引組成
創建與索引:
自定義索引:b=pd.Series([9,8,7,6],index=[‘a’,‘b’,‘c’,‘d’])
a 9
b 8
c 7
d 6
dtype: int64
默認索引:b=pd.Series([9,8,7,6])
0 9
1 8
2 7
3 6
dtype: int64
生成,創建方法:
標量創建:
s=pd.Series(25,index=['a','b','c'])
a 25
b 25
c 25
dtype: int64
字典創建:
d=pd.Series(dict)
生成的Series索引爲字典的鍵,一 一對應字典的數值
或
e=pd.Series({'a':1,'b':2,'c':3},index=['c','a','b','d'])
c 3
a 1
b 2
d NaN
dtype: float32
ndarray創建:
n=pd.Series(np.arang(23))
n=pd.Series(np.arange(5),index=np.arange(9,4,-1))
0 9
1 8
2 7
3 6
4 5
dtype: int32
基本操作:
索引:
b.index返回的是index類型數據
Index(['a', 'b', 'c', 'd'], dtype='object')
b.values返回的是array數據
<PandasArray> [9, 8, 7, 6] Length: 4, dtype: int64
現在有b=pd.Series([9,8,7,6],index=[‘a’,‘b’,‘c’,‘d’])
有兩種索引方式,一種是自定義索引b[‘a’]=9,一種是自動索引b[0]=9
在索引時,必須使用同一套索引。
在同時對多個元素進行索引時,返回一個Series。
例如:
b[['a','b',0]]#混合使用時當做自定義索引
a 9
b 8
0 NaN
切片:切片的返回依然是一個Series類型
b[:3]
a 9
b 8
c 7
dtype :int64
運算:
b[b>b.median()]
a 9
b 8
np.exp(b)
索引不變,值進行指數運算
同字典一樣,可以使用保留字in和.get()方法:
在字典中,判斷對象是否處於鍵中,而Series判斷是否存在自定義索引列表中:
'c' in b
True
0 in b
False
b.get('f',100)提取標籤f對應的數值,要是不存在則返回100
對齊操作:
b=pd.Series([1,2,3,4],index=['a','b','c','d'])
v=pd.Series([1,2,3,4],index=['a','z','c','k'])
b+v
a 2.0
b NaN
c 6.0
d NaN
k NaN
z NaN
dtype: float64
name屬性:
b.name="這是Series對象"
b.index.name="索引列"
則b顯示爲
索引列
a 1
b 2
c 3
d 4
Name: 這是Series對象, dtype: int64
修改:
b[‘a’]=12,此時索引a對應的值已經修改
b[‘a’,‘b’]=12,此時a,b對應的值都修改爲12