Python學(xué)習(xí)筆記之pandas索引列、過濾、分組、求和功能示例
本文實(shí)例講述了Python學(xué)習(xí)筆記之pandas索引列、過濾、分組、求和功能。分享給大家供大家參考,具體如下:
解析html內(nèi)容,保存為csv文件
//www.dbjr.com.cn/article/162401.htm
前面我們已經(jīng)把519961(基金編碼)這種基金的歷史凈值明細(xì)表html內(nèi)容抓取到了本地,現(xiàn)在我們還是需要 解析html,取出相關(guān)的值,然后保存為csv文件以便pandas
來統(tǒng)計(jì)分析。
from bs4 import BeautifulSoup import os import csv # 使用 BeautifulSoup 解析html內(nèi)容 def getFundDetailData(html): soup = BeautifulSoup(html,"html.parser") rows = soup.find("table").tbody.find_all("tr") result = [] for row in rows: tds=row.find_all('td') result.append({"fcode": '519961' ,"fdate": tds[0].get_text() , "NAV": tds[1].get_text() , "ACCNAV": tds[2].get_text() , "DGR": tds[3].get_text() , "pstate":tds[4].get_text() , "rstate": tds[5].get_text() } ) return result # 把解析之后的數(shù)據(jù)寫入到csv文件 def writeToCSV(): data_dir = "../htmls/details" all_path = os.listdir(data_dir) all_result = [] for path in all_path: if os.path.isfile(os.path.join(data_dir,path)): with open(os.path.join(data_dir,path),"rb") as f: content = f.read().decode("utf-8") f.close() all_result = all_result + getFundDetailData(content) with open("../csv/519961.csv","w",encoding="utf-8",newline="") as f: writer = csv.writer(f) writer.writerow(['fcode', 'fdate', 'NAV', "ACCNAV", 'DGR', 'pstate', "rstate"]) for r in all_result: writer.writerow([r["fcode"], r["fdate"], r["NAV"], r["ACCNAV"], r["DGR"], r["pstate"], r["rstate"]]) f.close()
# 執(zhí)行 writeToCSV()
pandas 排序、索引列
# coding: utf-8 import pandas if __name__ == "__main__" : # 讀取csv文件 創(chuàng)建pandas對象 pd = pandas.read_csv("./csv/519961.csv", dtype={"fcode":pandas.np.str_}, index_col="fdate") # 把 fdate 這列設(shè)置為 索引列 # 根據(jù)索引列 倒序 print(pd.sort_index(ascending=False))
既然fdate
列設(shè)置為了索引列,那么如果根據(jù)索引獲取呢?
# 讀取csv文件 創(chuàng)建pandas對象 pd = pandas.read_csv("./csv/519961.csv", dtype={"fcode":pandas.np.str_}, index_col="fdate") # 把 fdate 這列設(shè)置為 索引列 pd.index = pandas.to_datetime(pd.index) print(pd["2017-11-29 "]) # 2017-11-29 519961 1.189 1.189 -1.00% 限制大額申購 開放贖回
2、直接指定fdate
列就是日期類型
# 讀取csv文件 創(chuàng)建pandas對象 pd = pandas.read_csv("./csv/519961.csv", dtype={"fcode":pandas.np.str_}, index_col="fdate", parse_dates=["fdate"]) # 指明fdate是日期類型 print(pd["2017-11-29 "]) # 2017-11-29 519961 1.189 1.189 -1.00% 限制大額申購 開放贖回
打印索引:
print(pd.index) # 打印 索引
可以看出是DatetimeIndex
的索引:
DatetimeIndex(['2015-08-13', '2015-08-12', '2015-08-11', '2015-08-10', '2015-08-07', '2015-08-06', '2015-08-05', '2015-08-04', '2015-08-03', '2015-07-31', ... '2015-07-02', '2015-07-01', '2015-06-30', '2015-06-29', '2015-06-26', '2015-06-25', '2015-06-24', '2015-06-23', '2015-06-19', '2015-06-18'], dtype='datetime64[ns]', name='fdate', length=603, freq=None)
3、索引的高級用法
# 取出 2017年7月的 全部數(shù)據(jù) print(pd["2017-07"]) # 取出 2017年7月到9月的 數(shù)據(jù) print(pd["2017-07":"2017-09"]) # 到2015-07的數(shù)據(jù) print(pd[:"2015-07"]) # 取出截至到2015-07的數(shù)據(jù) # 然后 倒序 print(pd[:"2015-7"].sort_index(ascending=False))
獲取基金日增長率下跌次數(shù)最多的月份
result = pd[pd["DGR"].notnull()] # DGR一定要有值 # 過濾掉DGR值里的%號,最后取出小于0的值(負(fù)數(shù)就表示增長率下跌了 ) result = result[result['DGR'].str.strip("%").astype(pandas.np.float)<0] # 按照月份 統(tǒng)計(jì)DGR跌的次數(shù) result = result.groupby(lambda d:d.strftime("%Y-%m")).size() # 對DGR跌的次數(shù) 倒序,然后取出前面第一個(gè) result = result.sort_values(ascending=False).head(1) print(result) # 2016-04 12 意思就是2016年4月份 是該基金DGR下跌次數(shù)最多的月份
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python 在右鍵菜單中加入復(fù)制目標(biāo)文件的有效存放路徑(單斜杠或者雙反斜杠)
這篇文章主要介紹了python 在右鍵菜單中加入復(fù)制目標(biāo)文件的有效存放路徑(單斜杠或者雙反斜杠),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04Python中輸入若干整數(shù)以逗號間隔實(shí)現(xiàn)統(tǒng)計(jì)每個(gè)整數(shù)出現(xiàn)次數(shù)
這篇文章主要介紹了Python中輸入若干整數(shù)以逗號間隔實(shí)現(xiàn)統(tǒng)計(jì)每個(gè)整數(shù)出現(xiàn)次數(shù)的相關(guān)資料,需要的小伙伴可以參考一下,希望對你有所幫助2022-04-04Pytorch中如何調(diào)用forward()函數(shù)
這篇文章主要介紹了Pytorch中如何調(diào)用forward()函數(shù)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Python實(shí)現(xiàn)GUI學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)GUI學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01python中的psutil模塊詳解(cpu、內(nèi)存、磁盤情況、結(jié)束指定進(jìn)程)
這篇文章主要介紹了python中的psutil(cpu、內(nèi)存、磁盤情況、結(jié)束指定進(jìn)程),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04Python正則替換字符串函數(shù)re.sub用法示例
這篇文章主要介紹了Python正則替換字符串函數(shù)re.sub用法,結(jié)合實(shí)例形式分析了正則替換字符串函數(shù)re.sub的功能及簡單使用方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01