Pandas模塊
1、什么是pandas
pandas是基於numpy構建的,用來做數據分析的
2、pandas能干什么
- 具備對其功能的數據結構DataFrame,Series
- 集成時間序列功能
- 提供豐富的數學運算和操作
- 靈活處理缺失數據
3、怎么用pandas
安裝引用
pip install pandas
import pandas as pd
Series
一種類似於一維數組的對象,由一組數據和一組與之相關的數據標簽(索引)組成
#創建方法
pd.Series([1,2,3,4,5]) ##將數組索引以及數組的值打印出來,索引在左,值在右
pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
pd.Series({'a':1,'b':2})
pd.Series(0,index=['a','b','c'])
缺失數據
- dropna() 過濾掉值為Nan的行
- fill() 填充缺失數據
- isnull() 返回布爾數組,缺失值對應為True
- notnull() 返回布爾數組,缺失值對應為False
Series特性
從ndarray創建Series:Series(arr)
arr=np.arange(10)
sr=pd.Series(arr)
與標量(數字)進行運算
srx=sr*2
兩個Series運算
sr*srx
布爾值過濾
sr[sr>3]
統計函數:mean(),sum(),cumsum()
支持字典的特性
從字典創建Series:Series(dic)
dic={'a':1,'b':2,'c':3,'d':4,'e':5}
dic_arr=pd.Series(dic)
in運算
for i in dic_arr:
print(i)
鍵索引
dic_arr=[['a','b']]
鍵切片
dic_arr['a':'c']
其他函數
dic_arr.get('a',default=0)
整數索引
sr=pd.Series(np.arange(10))
sr1=sr[4:].copy()
-
loc屬性 以標簽解釋
-
iloc屬性 以下標解釋
sr1.iloc[1]
sr1.loc[3]
Series數據對齊
sr1=pd.Series([10,20,30],index=['a','b','c'])
sr2=pd.Series([30,20,10].index=['c','b','a'])
sr1+sr2
#將兩個Series對象相加將缺失值設為0
sr1=pd.Series([10,20,30],index=['a','b','c'])
sr2=pd.Series([30,20,10].index=['c','b','a','d'])
sr1.add(sr2,fill_value=0)
#靈活的算術方法:add,sub,div,mul
DataFrame
DataFrame是一個表格型的數據結構,相當於一個二維數組,含有一組有序的列。他可以被看做由Series組成的字典,並且公用一個索引
創建方式
pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
data=pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
pd.DataFrame(data,columns=['one','two'])
pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3],index=['b','a','c'])})
查看數據
常用屬性和方法
-
index獲取行索引
-
columns獲取列索引
-
T轉置
-
values獲取值索引
-
describe獲取快速統計
數組名.index 數組名.columns 數組名.T
數組名.values 數組名.describe
索引和切片
- DataFrame有行索引和列索引
- DataFrame可以通過標簽和位置兩張方法進行索引和切片
#兩個中括號
import tushare as ts
data =ts.get_k_data('000001')
data['open'][:10] #先取列再去行
data[:10]['open']
#使用loc、iloc屬性
data.loc[:10,'open':'low'] #用標簽取值
data.iloc[:10,1:5] #用下標取值
時間對象處理
處理時間對象可能是我們在進行數據分析的過程中最常見的,我們會遇到各種格式的時間序列,也需要處理各種格式的時間序列
時間序列類型
-
時間戳:特定時刻
-
國定時間:如2017年2月
-
時間間隔:起始時間-結束時間