使用 pd.read_excel()方法读取数据,并输出。
(1) 注意:如果没有列名,请使用参数设置列名序列为:[“菜名”, “地址”, “价格”,“单 位”,“日期”]
(2)输出数据表中数据前 5 行
(3)输出数据表中数据前 5 行,只包含列地址、价格与日期。
(4)使用 df.describe()查看数据表的整体统计信息
(5)输出数据表中的统计的不同地址(地址列去重)。
import numpy as py import pandas import requests import json import time from openpyxl import Workbook url = r"https://www.gznw.com/eportal/ui?moduleId=ab59857100d84dcca372ff4473198d88&struts.portlet.mode=view&struts.portlet.action=/portlet/priceFront!queryFrontList.action&pageSize=20&pageNum=1&recruitType=1&productName=%E9%B2%9C%E9%B8%A1%E8%9B%8B&areaCode=22572&startTime=20230201&endTime=20230404" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 " "Safari/537.36 Edg/111.0.1661.54 " } response = requests.get(url=url, headers=headers) res = json.loads(response.text) sulidata = res['rows'] wb = Workbook() ws = wb.worksheets[0] ws.append(["产品名称", "价格类型", "价格", "单位", "市场名称", "发布时间"]) for lists in sulidata: name, style, price, danwei, address, time1 = ( lists['v0027'], lists['v0036'], lists['v0005'], lists['v0014'], lists['v0031'], lists['v0004']) print(name, price, address, time1) index = time1.index(".") date_time = time.strptime(time1[:index], '%Y-%m-%d %H:%M:%S') date_time1 = time.strftime('%Y年%m月%d日 %H时%M分%S秒', date_time) print(date_time1) ws.append([name, style, price, danwei, address, date_time1]) wb.save("价格爬取.xlsx")
将东西用matplotlib画图画出来
代码如下
import numpy as np import pandas as pd from pylab import mpl import matplotlib.pyplot as plt # #groupby帮助文档:https://pandas.pydata.org/docs/user_guide/groupby.html?highlight=plot # #1groupby的基本步骤:split,apply,combin mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体为黑体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 df=pd.read_excel("农产品数据1.xlsx",header=0) print(df.loc[0:5]) group = df.groupby('市场') # df['日期1']=pd.to_datetime(df['发售时间']).dt.date df['日期']=df['发售时间'].str[0:8] n=0 for name,value in group: g3=value.groupby(df['日期'])['价格'].mean() x=np.arange(len(g3.index))+n*0.3 plt.bar(x,g3.values,width=0.3,label=name) plt.xticks(x,g3.index,rotation=45) n=n+1 plt.xlabel("时间") plt.ylabel("平均价格") plt.title("贵阳各地区鸡蛋平均价格") plt.legend() plt.show()
结果展示