gpt4 book ai didi

Python Pandas 比较两个数据框然后编辑

转载 作者:行者123 更新时间:2023-12-04 20:48:49 25 4
gpt4 key购买 nike

首先抱歉,如果这是重复的,我是初学者,所以我不太了解别人问题的全部含义。
我正在尝试为一个学校项目制作一个脚本,该脚本通过一个带有多个链接的大 Excel 文件运行,并从网页上抓取价格,将其与 Excel 中实际价格列中的价格进行比较。如果发现没有区别:太好了!但如果是这样,它应该用它刚刚刮掉的新价格来编辑价格。
例如

Excel file : 

| Link | Price |
| -------- | -------------- |
| Product1 | 119 |
| Product2 | 89 |

Scraped data :

| Price |
| -------------- |
| 119 |
| 91 |

If this scenario happens, the Excel file should be edited to become like this :

| Link | Price |
| -------- | -------------- |
| Product1 | 119 |
| Product2 | 91 |
现在我只能将价格刮成一个列表并将Excel文件变成一个数据框,但我真的不知道下一步该怎么做......
这是我的代码
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

b =[]
tableau = pd.read_excel (r'PriceTrackerTrails\liens.xlsx')

links = pd.DataFrame(tableau, columns=['prix','liens'])

for i in links.index:
html = requests.get(links['liens'][i]).text
soup = bs(html, 'lxml')
a = soup.find('span', {"itemprop":"price"}).text
b.append(a)

print(links['prix'])
print(b)
输出 :
0    139,00
1 98
Name: prix, dtype: object
['139,00', '112,00']
Excel 文件看起来像这样: Excel links source file
先感谢您 !

最佳答案

在 for 循环中,将 links['prix'] 中的值更新为 a 中的值,如下所示:

for i in links.index:
html = requests.get(links['liens'][i]).text
soup = bs(html, 'lxml')
a = soup.find('span', {"itemprop":"price"}).text
b.append(a)
links.loc[i, 'prix'] = a
要访问哪些行有价格更新,我会以不同的方式执行此操作,并在存储新价格的链接数据框中创建一个新列,而不是覆盖“prix”列中的值,并创建列表 b .这样可以更容易地验证数据,并且不需要单独的列表 b 。为此,您只需将 loc 方法更改为新的列名:
for i in links.index:
html = requests.get(links['liens'][i]).text
soup = bs(html, 'lxml')
a = soup.find('span', {"itemprop":"price"}).text
b.append(a)
links.loc[i, 'prix_new'] = a
然后创建一个新的数据框,其中仅包含价格发生变化的行,如下所示:
price_updated = links[links['prix']!=links['prix_new']].reset_index()
reset_index 使这个新数据帧的行索引从 0 开始(默认情况下会复制)。如果要保留行索引以使其与 links 数据帧匹配,则将 reset_index 替换为 copy,这样您就不会收到 SettingWithCopyWarning 警告,即有关更改数据帧中切片副本的值的警告。

关于Python Pandas 比较两个数据框然后编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70690170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com