pandas 基本使用
介紹
是什么
pandas是一個強大的Python數據分析的工具包,它是基于NumPy構建的。
關于NumPy,參考這里。
主要功能
安裝
pip install pandas
引用
import pandas as pd
Series
Series是一種類似于一維數組的對象,由一組數據和一組與之相關的數據標簽(索引)組成。
Series比較像列表(數組)和字典的結合體,有序,同時支持索引和鍵。
創(chuàng)建
# 默認創(chuàng)建 sr = pd.Series([1,5,-6,9]) """ 默認生成整數索引 0 1 1 5 2 -6 3 9 dtype: int64 """# 指定標簽創(chuàng)建 pd.Series([1,5,-6,9], index=['a', 'b', 'c', 'd']) """ a 1 b 5 c -6 d 9 dtype: int64 """# 以字典方式創(chuàng)建 pd.Series({'a':1, 'b':2}) """ a 1 b 2 dtype: int64 """# 取值數組和索引數組:values屬性和index屬性 sr = pd.Series([1,5,-6,9]) sr.index sr.values """ RangeIndex(start=0, stop=4, step=1) array([ 1, 5, -6, 9], dtype=int64) """sr = pd.Series([1,5,-6,9], index=['a', 'b', 'c', 'd']) sr.index sr.values """ 說明,字符串是object Index(['a', 'b', 'c', 'd'], dtype='object') array([ 1, 5, -6, 9], dtype=int64) """特性
Series支持NumPy模塊的特性(下標)
從ndarray創(chuàng)建Series:Series(arr)
a = np.array([1,2,3,4]) sr = pd.Series(a, index=['a','b','c','d']) """ a 1 b 2 c 3 d 4 dtype: int32 """?
與標量運算:sr*2
sr = pd.Series([1,2,3,4], index=['a','b','c','d']) sr * 2 """ a 2 b 4 c 6 d 8 dtype: int32 """?
兩個Series運算:sr1+sr2
sr1 = pd.Series([1,2,3,4]) sr2 = pd.Series([3,1,3,4]) sr1 + sr2 """ 0 4 1 3 2 6 3 8 dtype: int64 """?
索引:sr[0], sr[[1,2,4]]
sr = pd.Series([1,5,-6,9,8], index=['a', 'b', 'c', 'd', 'e'])sr[0] # 1 簡單索引 sr[[1,2,4]] # 花式索引 """ b 5 c -6 e 8 dtype: int64 """?
切片:sr[0:2](切片依然是視圖形式),顧頭不顧尾
sr = pd.Series([1,5,-6,9,8], index=['a', 'b', 'c', 'd', 'e']) sr[0:2] """ a 1 b 5 dtype: int64 """?
通用函數:np.abs(sr) ,參考num.py
布爾值過濾:sr[sr>0]
統(tǒng)計函數:mean() sum() cumsum()
# cumsum() 返回前綴和sr = pd.Series([1,2,3,4,5]) sr.cumsum() """ 0 1 1 3 2 6 3 10 4 15 dtype: int64 """?
Series支持字典的特性(標簽)
從字典創(chuàng)建Series:Series(dic),
in運算:’a’ in sr、for x in sr
sr = pd.Series([1,2,3,4], index=['a','b','c','d']) 'a' in sr # True sr.get('a') # 1 # 注意,不同與python的字典類型,循環(huán)Series對象,結果就是值,而不是鍵for i in sr:print(i) """ 1 2 3 4 """?
鍵索引:sr[‘a’], sr[[‘a’, ‘b’, ‘d’]]
sr = pd.Series([1,2,3,4], index=['a','b','c','d']) sr['a'] # 1# 花式索引sr[['a','b','d']] """ a 1 b 2 d 4 dtype: int64 """?
鍵切片:sr[‘a’:’c’],顧頭顧尾
sr = pd.Series([1,2,3,4], index=['a','b','c','d']) sr['a':'c'] """ 等同于sr[0:3],只不過通過標簽索切片,顧頭顧尾: a 1 b 2 c 3 dtype: int64 """?
其他函數:get(‘a’, default=0)等
sr = pd.Series([1,2,3,4], index=['a','b','c','d']) sr.get('f', default=0) # 0?
整數索引
Series對象的索引既可以是標簽,又可以是整數。
特別注意:如果索引是整數類型,則根據整數進行數據操作時總是面向標簽的!(即如果索引即可以解釋成下標,有可以是標簽時,以標簽解釋)
解決方案:sr.loc() 以標簽解釋; sr.iloc() 以下標解釋
import pandas as pd import numpy as npsr = pd.Series(np.random.uniform(1,10,5)) """ 0 2.699248 1 7.649924 2 5.232440 3 6.690911 4 5.734944 dtype: float64 """ sr[-1] # 報錯,KeyError: -1 因為默認以標簽解釋,而-1這個標簽不存在sr.iloc[-1] # 5.734944 (因為是隨機數,這里值是隨機的) sr.loc[-1] # KeyError: 'the label [-1] is not in the [index]'Series數據對齊
Series對象運算時,會按索引進行對齊然后計算。如果存在不同的索引,則結果的索引是兩個操作數索引的并集
# 索引都存在時,按標簽對齊 sr1 = pd.Series([12,23,34], index=['c','a','d']) sr2 = pd.Series([11,20,10], index=['d','c','a',]) sr1+sr2 """ a 33 c 32 d 45 dtype: int64 """#存在不同的索引時,缺失值返回NaN sr3 = pd.Series([11,20,10,14], index=['d','c','a','b']) sr1+sr3 """ a 33.0 b NaN # 缺失值 c 32.0 d 45.0 dtype: float64 """# 如何在兩個Series對象進行算術運算時將缺失值設為0? # 使用函數(add, sub, div, mul),而不是運算符,指定fill_value參數 sr1.add(sr3, fill_value=0) """ a 33.0 b 14.0 # 缺失值賦值0,使不影響運算結果 c 32.0 d 45.0 dtype: float64 """Series缺失數據
缺失數據:
使用NaN(Not a Number)來表示缺失數據。其值等于np.nan。內置的None值也會被當做NaN處理。
處理缺失數據的相關方法:
DataFrame
DataFrame是一個表格型的數據結構(二維數據結構),含有一組有序的列。DataFrame可以被看做是由Series組成的字典,并且共用一個索引。
創(chuàng)建
# 通過字典的方式創(chuàng)建,key相當于列名(也可以理解為數據庫的字段),自動創(chuàng)建整數索引。 pd.DataFrame({'one': [1,2,3,4,], 'two': [4,3,2,1]}) """one two 0 1 4 1 2 3 2 3 2 3 4 1 """# 通過字典和Series對象創(chuàng)建: 取Series對象中標簽的并集作為索引,缺失值為NaN pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=['b','a','c','d'])}) """one two a 1.0 2 b 2.0 1 c 3.0 3 d NaN 4 """DataFrame的類似與數據庫中的表,我們一般很少手動創(chuàng)建DataFrame,而是從文件中讀取,這個后面會寫到。
csv文件的讀取和寫入:
常用屬性及方法
索引和切片
df = pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([5,4,7,2],index=['b','a','c','d']),'three':pd.Series([6,8,3,9], index=['a','b','c','d'])}) """one three two a 1.0 6 4 b 2.0 8 5 c 3.0 3 7 d NaN 9 2 """######## 位置索引 iloc ################################# 取一維數據(Series對象),按行取 df.iloc[3] # iloc下標索引 """ one NaN three 9.0 two 2.0 Name: d, dtype: float64 """# 取某個值 df.iloc[3,1] # 9 3行1列# 切某個區(qū)域;逗號左邊是行,右邊是列 df.iloc[0:3,1:] """three two a 6 4 b 8 5 c 3 7 """# 花式索引 df.iloc[[0,3],[0,2]] """one two a 1.0 4 d NaN 2 """####### 標簽索引 先列后行 ############################# 取一維數據(Series對象),按列取 df['one'] """ a 1.0 b 2.0 c 3.0 d NaN Name: one, dtype: float64 """# 取某個值, 按標簽,先列后行 df['two']['a'] # 4 two列a行# 注意:先行后列時,千萬不要連用兩個中括號, 除非指定loc df['b']['two'] # 報錯 KeyError: 'b' df.loc['b']['two'] # 5###### 布爾索引 ###################################df[df['one']>1] """one three two b 2.0 8 5 c 3.0 3 7 """# isin([]) 判斷在不在 df[df['two'].isin([2,4])] """one three two a 1.0 6 4 d NaN 9 2 """# 不符合條件全部設置缺失值 df[df>6] """one three two a NaN NaN NaN b NaN 8.0 NaN c NaN NaN 7.0 d NaN 9.0 NaN """""" 總結: 通過位置取值時,加iloc指定 通過標簽取值時,先列后行;如果要先行后列,加loc指定 (因為DateFrame類似于數據庫中的表,因此通過列(字段)取值顯然更有意義) """數據對齊與缺失數據
DataFrame對象在運算時,同樣會進行數據對齊,結果的行索引與列索引分別為兩個對象的行索引與列索引的并集。
DataFrame處理缺失數據的方法:
- axis=0 行軸(默認值), axis=1 列軸
- how=’any’ 指定軸中只要有一個nan,就刪掉;how=’all’ 指定軸全是nan,才刪掉
其他常用方法(Series和DataFrame)
- axis=0 取列平均值(默認),axis=1 取行平均值
- skpna默認True, False沒意義,只要有NaN, 平均值值為NaN
- by指定列(必須參數,且必須是列),ascending=False 倒序
層次化索引
層次化索引是Pandas的一項重要功能,它使我們能夠在一個軸上擁有多個索引級別。
pd.Series(np.random.rand(9), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'],[1,2,3,1,2,3,1,2,3]]) """ a 1 0.8695982 0.4110183 0.489448 b 1 0.8051592 0.2025903 0.926205 c 1 0.7798332 0.8603883 0.906701 dtype: float64 """從文件讀取與寫入
讀文件
讀取文件:從文件名、URL、文件對象中加載數據
更多格式,通過在ipython中輸入pd.read_*? 查看
讀取文件函數主要參數:
sep 指定分隔符,可用正則表達式如’\s+’
實例參看本文最后。
寫文件
寫入到文件:
主要參數:
其它文件類型:
json, XML, HTML, 數據庫
pandas轉換為二進制文件格式(pickle):
時間對象
時間序列類型:
python標準庫:datetime :
第三方包:dateutil:
pandas自帶這個包,更易用,不用指定格式,常見英文日期格式都支持:dateutil.parser.parse()
import dateutildateutil.parser.parse('2001-01-01') # datetime.datetime(2001, 1, 1, 0, 0) 解析為日期對象dateutil.parser.parse('2001-01-01 09:30:00') # datetime.datetime(2001, 1, 1, 9, 30)dateutil.parser.parse('200/01/01') # datetime.datetime(200, 1, 1, 0, 0)時間對象處理
產生時間對象數組:date_range
- 默認為’D(ay)’,可選H(our),W(eek),B(usiness),S(emi-)M(onth),(min)T(es), S(econd), A(year),…
時間序列
概念
時間序列就是以時間對象為索引的Series或DataFrame。
datetime對象作為索引時是存儲在DatetimeIndex對象中的。
功能
比如:拿到一份股票的歷史數據601318.csv,讀入進行處理
# index_col='date' 指定date列為索引列(否則無法通過日期范圍切片) # parse_dates=['date'], 將date列解析為時間對象 df = pd.read_csv('601318.csv',index_col='date', parse_dates=['date'], na_values=['None'])# 根據時間范圍切片 df['2013-11':'2014']練習
選出601318.csv中所有陽線的日期
df = pd.read_csv('601318.csv',index_col='date', # 日期列作為索引parse_dates=['date'],na_values=['None']) df[df['close'] > df['open']].index # 篩選出收盤價大于開盤價的行,然后取日期索引 """ DatetimeIndex(['2007-03-06', '2007-03-07', '2007-03-13', '2007-03-14','2007-03-16', '2007-03-26', '2007-03-27', '2007-03-28',...'2017-07-19', '2017-07-20', '2017-07-24', '2017-07-27','2017-07-31', '2017-08-01'],dtype='datetime64[ns]', name='date', length=1228, freq=None) """# 結果還以通過.values 轉為數組,或者.tolist() 轉為列表?
新增兩列,存5日均線和30日均線
df['ma5'] = np.nan # 初始化為NaN df['ma10'] = np.nanfor i in range(4, len(df)):df.loc[df.index[i], 'ma5'] = df['close'][i-4:i+1].mean() # 取收盤價那一列前4天到當天的均值,賦給當天ma5for i in range(10, len(df)):df.loc[df.index[i], 'ma10'] = df['close'][i-9:i+1].mean()?
選出所有金叉日期和死叉日期
?
?
總結
以上是生活随笔為你收集整理的pandas 基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自制飞机
- 下一篇: 路由器刷机常见第三方固件及管理前端种类(