Python学习笔记之pandas索引列、过滤、分组、求和功能示例

yipeiwu_com6年前Python基础

本文实例讲述了Python学习笔记之pandas索引列、过滤、分组、求和功能。分享给大家供大家参考,具体如下:

解析html内容,保存为csv文件
/post/162401.htm

前面我们已经把519961(基金编码)这种基金的历史净值明细表html内容抓取到了本地,现在我们还是需要 解析html,取出相关的值,然后保存为csv文件以便pandas来统计分析。

from bs4 import BeautifulSoup
import os
import csv
# 使用 BeautifulSoup 解析html内容
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
# 把解析之后的数据写入到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()

# 执行
writeToCSV()

pandas 排序、索引列

# coding: utf-8
import pandas
if __name__ == "__main__" :
  # 读取csv文件 创建pandas对象
  pd = pandas.read_csv("./csv/519961.csv", dtype={"fcode":pandas.np.str_}, index_col="fdate") # 把 fdate 这列设置为 索引列
  # 根据索引列 倒序
  print(pd.sort_index(ascending=False))

既然fdate列设置为了索引列,那么如果根据索引获取呢?

# 读取csv文件 创建pandas对象
pd = pandas.read_csv("./csv/519961.csv", dtype={"fcode":pandas.np.str_}, index_col="fdate") # 把 fdate 这列设置为 索引列
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文件 创建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月的 全部数据
print(pd["2017-07"])
# 取出 2017年7月到9月的 数据
print(pd["2017-07":"2017-09"])
# 到2015-07的数据
print(pd[:"2015-07"])
# 取出截至到2015-07的数据
# 然后 倒序
print(pd[:"2015-7"].sort_index(ascending=False))

获取基金日增长率下跌次数最多的月份

result = pd[pd["DGR"].notnull()] # DGR一定要有值
# 过滤掉DGR值里的%号,最后取出小于0的值(负数就表示增长率下跌了 )
result = result[result['DGR'].str.strip("%").astype(pandas.np.float)<0]
# 按照月份 统计DGR跌的次数
result = result.groupby(lambda d:d.strftime("%Y-%m")).size()
# 对DGR跌的次数 倒序,然后取出前面第一个
result = result.sort_values(ascending=False).head(1)
print(result) # 2016-04  12 意思就是2016年4月份 是该基金DGR下跌次数最多的月份

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

利用Anaconda完美解决Python 2与python 3的共存问题

前言 现在Python3 被越来越多的开发者所接受,同时让人尴尬的是很多遗留的老系统依旧运行在 Python2 的环境中,因此有时你不得不同时在两个版本中进行开发,调试。 如何在系统中同...

Python中断言Assertion的一些改进方案

Python Assert 为何不尽如人意? Python中的断言用起来非常简单,你可以在assert后面跟上任意判断条件,如果断言失败则会抛出异常。 >>>...

Python自动生成代码 使用tkinter图形化操作并生成代码框架

Python自动生成代码 使用tkinter图形化操作并生成代码框架

背景 在写代码过程中,如果有频繁重复性的编码操作,或者可以Reuse的各类代码,可以通过Python写一个脚本,自动生成这类代码,就不用每次手写、或者copy了。 比如新建固定的代码框架...

python实现数据图表

python实现数据图表

平时压力测试,生成一些数据后分析,直接看 log 不是很直观,前段时间看到公司同事分享了一个绘制图表python 模块 : plotly, 觉得很实用,利用周末时间熟悉下。 plotl...

深入浅析ImageMagick命令执行漏洞

深入浅析ImageMagick命令执行漏洞

00 前言 什么是ImageMagick? ImageMagick是一个功能强大的开源图形处理软件,可以用来读、写和处理超过90种的图片文件,包括流行的JPEG、GIF、 PNG、PDF...