w_data=data.groupby('update_time and 店名=="欧莱雅"')['totalPrice']
时间: 2024-02-01 12:02:02 浏览: 30
这是一个针对一个名为"data"的数据集进行的分组操作,按照"update_time"和"店名"两个列的值进行分组,并获取每个分组中"totalPrice"这一列的数据。具体来说,该代码使用了pandas库中的groupby函数,将数据集按照指定的列进行分组,并使用['totalPrice']选取了需要获取的数据列。
相关问题
import requests from bs4 import BeautifulSoup import openpyxl class LianJiaSpider(): def __init__(self): self.url = 'https://bj.lianjia.com/ershoufang/pg{0}/' self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.12022 SLBChan/109'} def send_request(self, url): resp = requests.get(url, headers=self.headers) if resp.status_code == 200: return resp def parse_html(self, resp): lst = [] html = resp.text bs = BeautifulSoup(html, 'lxml') ul = bs.find('ul', class_='sellListContent') li_list = ul.find_all('li') for item in li_list: title = item.find('div', class_='title').text positionInfo = item.find('div', class_='positionInfo').text address = item.find('div', class_='address').text followInfo = item.find('div', class_='followInfo').text tag = item.find('div', class_='tag').text totalPrice = item.find('div', class_='totalPrice totalPrice2').text unitPrice = item.find('div', class_='unitPrice').text # print(unitPrice) lst.append((title, positionInfo, address, followInfo, tag, totalPrice, unitPrice)) print(lst) self.save(lst) def save(self, lst): wb = openpyxl.Workbook() sheet = wb.active for row in lst: sheet.append(row) continue wb.save('D:/爬虫/链家.csv') def start(self): for i in range(1, 5): full_url = self.url.format(i) resp = self.send_request(full_url) #print(resp.text) self.parse_html(resp) if __name__ == '__main__': lianjia = LianJiaSpider() lianjia.start()使用以上代码爬取数据保存到文件中只显示最后一页30条数据,前面页码的数据都被覆盖了,如何更改
在 `save` 方法中,每次循环都重新创建了一个新的 `Workbook` 对象,因此在保存数据时会覆盖之前的数据。您可以将 `Workbook` 对象的创建放在 `__init__` 方法中,这样每次保存数据时都可以使用同一个 `Workbook` 对象。另外,您还可以将文件名中的页码部分替换为变量 `i`,这样每次保存的文件都会有不同的文件名,不会被覆盖。修改后的代码如下:
```python
import requests
from bs4 import BeautifulSoup
import openpyxl
class LianJiaSpider():
def __init__(self):
self.url = 'https://bj.lianjia.com/ershoufang/pg{0}/'
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.12022 SLBChan/109'}
self.wb = openpyxl.Workbook()
self.sheet = self.wb.active
self.sheet.append(('标题', '位置', '地址', '关注信息', '标签', '总价', '单价'))
def send_request(self, url):
resp = requests.get(url, headers=self.headers)
if resp.status_code == 200:
return resp
def parse_html(self, resp):
html = resp.text
bs = BeautifulSoup(html, 'lxml')
ul = bs.find('ul', class_='sellListContent')
li_list = ul.find_all('li')
for item in li_list:
title = item.find('div', class_='title').text
positionInfo = item.find('div', class_='positionInfo').text
address = item.find('div', class_='address').text
followInfo = item.find('div', class_='followInfo').text
tag = item.find('div', class_='tag').text
totalPrice = item.find('div', class_='totalPrice totalPrice2').text
unitPrice = item.find('div', class_='unitPrice').text
self.sheet.append((title, positionInfo, address, followInfo, tag, totalPrice, unitPrice))
print('第{}页数据爬取完成'.format(i))
def save(self):
self.wb.save('D:/爬虫/链家_{}.csv'.format(i))
def start(self):
for i in range(1, 5):
full_url = self.url.format(i)
resp = self.send_request(full_url)
self.parse_html(resp)
self.save()
if __name__ == '__main__':
lianjia = LianJiaSpider()
lianjia.start()
```
在修改后的代码中,我将文件名改为了 `"D:/爬虫/链家_{}.csv".format(i)`,这样每次保存的文件名都会包含页码,不会被覆盖。同时,我将保存数据的操作从 `parse_html` 方法中分离出来,放在了单独的 `save` 方法中,并且在 `__init__` 方法中创建了 `Workbook` 对象和表头。这样就可以避免每次循环都重新创建一个新的 `Workbook` 对象,从而避免了数据被覆盖的问题。
import matplotlib.pyplot as plt import pandas as pd plt.rcParams['font.family']='sans-serif' plt.rcParams['font.sans-serif'] = ['Simhei'] plt.rcParams['axes.unicode_minus'] = False filename = "../task/ershoufang_jinan_utf8_clean.csv" names = ["id","communityName","areaName","total","unitPriceValue", "fwhx","szlc","jzmj","hxjg","tnmj", "jzlx","fwcx","jzjg","zxqk","thbl", "pbdt","cqnx","gpsj","jyqs","scjy", "fwyt","fwnx","cqss","dyxx","fbbj", "aa","bb","cc","dd"] miss_value = ["null","暂无数据"] df = pd.read_csv(filename,header=None, skiprows=[0],names=names,na_values=miss_value) 步骤一:二手房单价箱线图 通过箱线图分析二手房单价在各个区域的对比。 """各区域二手房单价箱线图""" #数据分组、数据运算和聚合 box_unitprice_area = df["unitPriceValue"].groupby(df["areaName"]) flag = True box_data = pd.DataFrame(list(range(21000)),columns=["start"]) for name,group in box_unitprice_area: box_data[name] = group del box_data["start"] fig = plt.figure(figsize=(12,7)) ax = fig.add_subplot(111) ax.set_ylabel("总价(万元)",fontsize=14) ax.set_title("各区域二手房单价箱线图",fontsize=18) box_data.plot(kind="box",fontsize=12,sym='r+',grid=True,ax=ax,yticks=[20000,30000,40000,50000,100000]) 可以对比济南各个区的二手房均价和分布。 步骤二:二手房总价箱线图 通过箱线图分析二手房总价在各个区域的对比。 参照下面的提示补全缺失的代码: # 仿照上面的代码,按地区对二手房总价进行归类
请将代码补充如下:
```python
"""各区域二手房总价箱线图"""
box_totalprice_area = df["total"].groupby(df["areaName"])
box_total_data = pd.DataFrame(list(range(21000)), columns=["start"])
for name, group in box_totalprice_area:
box_total_data[name] = group
del box_total_data["start"]
fig = plt.figure(figsize=(12,7))
ax = fig.add_subplot(111)
ax.set_ylabel("总价(万元)", fontsize=14)
ax.set_title("各区域二手房总价箱线图", fontsize=18)
box_total_data.plot(kind="box", fontsize=12, sym='r+', grid=True, ax=ax, yticks=[0, 100, 200, 300, 400])
```
这样就可以绘制各区域二手房总价的箱线图了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)