Python pandas实战:索引设置、日期过滤与分组统计详解

巷口听风
巷口听风
发布时间:2026-10-13 | 5人浏览过
原创

本文通过解析HTML并保存CSV文件的实例,演示如何使用Python pandas进行数据预处理。重点讲解将列设为索引、转换日期类型、利用索引进行高效数据过滤,以及通过分组统计找出特定指标(如基金日增长率)下跌频率最高的月份,提供完整的代码实现与逻辑分析。

pandas索引、过滤与分组统计实战

本文通过具体实例,详细解析Python中pandas库在索引列设置、数据过滤、分组操作及求和功能方面的应用,旨在为读者提供实用的参考代码与思路。

首先,我们需要解析HTML内容,并将其保存为CSV格式的文件。相关参考链接://www.jb51.net/article/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% 限制大额申购  开放赎回

日期类型转换与索引访问

第二步,直接指定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)

第三部分介绍索引的高级用法。


# 取出 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程序设计有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表