7.python資料分析與展示------Pandas庫入門
1.Pandas庫的介紹
Pandas是Python第三方庫,提供高效能易用資料型別和分析工具
import pandas as pd
Pandas基於Numpy實現,常與Numpy和Matplotlib一同使用
import pandas as pd d =pd.Series(range(20)) print(d) # 0 0 # 1 1 # 2 2 # 3 3 # 4 4 # 5 5 # 6 6 # 7 7 # 8 8 # 9 9 # 10 10 # 11 11# 12 12 # 13 13 # 14 14 # 15 15 # 16 16 # 17 17 # 18 18 # 19 19 # dtype: int64 d=d.cumsum() print(d) # 0 0 # 1 1 # 2 3 # 3 6 # 4 10 # 5 15 # 6 21 # 7 28 # 8 36 # 9 45 # 10 55 # 11 66 # 12 78 # 13 91 # 14 105# 15 120 # 16 136 # 17 153 # 18 171 # 19 190 # dtype: int64
兩個資料型別:Series,DataFrame
基於上述資料型別的各類操作 基本操作、運算操作、特徵類操作、關聯類操作
2.Pandas庫的Series型別
Series型別由一組資料及與之相關的資料索引組成可自定義索引
b=pd.Series([9,8,7,6],index=['a','b','c','d']) print(b) # a 9 # b 8 # c 7 # d 6 # dtype: int64
Series型別:
Series型別可以由如下型別建立:
•Python列表
•標量值
•Python字典
•ndarray
•其他函式
Series型別可以由如下型別建立:
•Python列表,index與列表元素個數一致
•標量值,index表達Series型別的尺寸
•Python字典,鍵值對中的“鍵”是索引,index從字典中進行選擇操作
•ndarray,索引和資料都可以通過ndarray型別建立
•其他函式,range()函式等
Series型別的基本操作
Series型別包括index和values兩部分
Series型別的操作類似ndarray型別
Series型別的操作類似Python字典型別
import pandas as pd b=pd.Series([9,8,7,6],index=['a','b','c','d']) print(b) # a 9 # b 8 # c 7 # d 6 # dtype: int64 print(b.index) #Index(['a', 'b', 'c', 'd'], dtype='object') print(b.values) #[9 8 7 6]
Series型別的操作類似ndarray型別:
•索引方法相同,採用[]
•NumPy中運算和操作可用於Series型別
•可以通過自定義索引的列表進行切片
•可以通過自動索引進行切片,如果存在自定義索引,則一同被切片
import pandas as pd import numpy as np b=pd.Series([9,8,7,6],index=['a','b','c','d']) print(b) # a 9 # b 8 # c 7 # d 6 # dtype: int64 print(b[3]) #6 print(b[:3]) # a 9 # b 8 # c 7 print(b[b>b.median()]) # a 9 # b 8 # dtype: int64 print(np.exp(b)) # a 8103.083928 # b 2980.957987 # c 1096.633158 # d 403.428793 # dtype: float64
Series型別的操作類似Python字典型別:
•通過自定義索引訪問
•保留字in操作
•使用.get()方法
import pandas as pd import numpy as np b=pd.Series([9,8,7,6],index=['a','b','c','d']) print(b['b']) #8 print('c' in b) #True print(0 in b) #False print(b.get('f',100)) #100
import pandas as pd import numpy as np b=pd.Series([9,8,7,6],index=['a','b','c','d']) a=pd.Series([1,2,3],['c','d','e']) print(a+b) # a NaN # b NaN # c 8.0 # d 8.0 # e NaN # dtype: float64
Series型別在運算中會自動對齊不同索引的資料
import pandas as pd import numpy as np b=pd.Series([9,8,7,6],index=['a','b','c','d']) print(b.name) #None b.name='Series物件' b.index.name='索引列' print(b) # 索引列 # a 9 # b 8 # c 7 # d 6 # Name: Series物件, dtype: int64
Series物件可以隨時修改並即刻生效
3.Pandas庫的DataFrame型別
DataFrame型別可以由如下型別建立:
•二維ndarray物件
•由一維ndarray、列表、字典、元組或Series構成的字典
•Series型別
•其他的DataFrame型別
①從二維ndarray物件建立
②從一維ndarray物件字典建立
③從列表型別的字典建立
4.Pandas庫的資料型別操作
.reindex()能夠改變或重排Series和DataFrame索引
Series和DataFrame的索引是Index型別 Index物件是不可修改型別
.drop()能夠刪除Series和DataFrame指定行或列索引