我的代码下面刮一个网站,并导出数据框到excel文件。但是,我需要从第一列中删除不必要的字符并将它们组合起来,这样就不需要在excel文件中重命名months。每一行都有一个来自网站的名称,HOZ18(2018年12月)“HOZ19(2019年12月)”,除了“\”之外,我对此不感兴趣。所以,我只想把12月18日,1月19日,2月20日等放在第一栏。你知道吗
from urllib.request import urlopen
import pandas as pd
import requests
from bs4 import BeautifulSoup
url = "https://shared.websol.barchart.com/quotes/quote.php?page=quote&sym=ho&x=13&y=8&domain=if&display_ice=1&enabled_ice_exchanges=&tz=0&ed=0"
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')
Contracts=[]
LastPrice=[]
data_rows = soup.findAll('tr')[2:]
for td in data_rows:
Contract = td.findAll('td')[0].text
Contracts.append(Contract)
LstPrice = td.findAll('td')[7].text
LastPrice.append(LstPrice)
df = pd.DataFrame({'Contracts': Contracts, 'Previous Settled': LastPrice})
0 Cash (HOY00) 2.1884
1 Dec \'18 (HOZ18) 2.2371
2 Jan \'19 (HOF19) 2.2238
3 Feb \'19 (HOG19) 2.2125
如果您希望将
Dec \'18 (HOZ18)
这样的字符串转换为December 18
,下面是一个解决方案。你知道吗1)定义一个函数来清除字符串:
2)使用
apply
将该函数应用于数据帧中的每一行。这里有一个不需要
.apply()
的选项。它假设我们面对的是21世纪的岁月,不确定这是否对你有用。它还将月份存储为一个数字,这可能很有用,如果没有,您可以删除该位。你知道吗给予:
相关问题 更多 >
编程相关推荐