我正在報廢一個HMTL表,最終的資料框架創建了一個需要清理和格式化的 "日期 "列。
我的范圍是將這一列轉換為一個資料列。
下面是我的資料框架:
在這一步之后,我想做的是清理Date列,并將此列轉換為pandas日期列。
有什么幫助嗎?
下面是如何制作這個表格的:
## web scrapping
import請求
import lxml.html as lh
import pandas as pd
url='https://markets.ft.com/data/funds/tearsheet/historical?s=LU0841585341:GBP'。
#創建一個句柄,page,以處理網站的內容。
page = requests.get(url)
#Store the contents of the website under doc[/span]。
doc = lh.fromstring(page.content)
#決議存盤在HTML的<tr>.</tr>之間的資料。
tr_elements = doc.xpath('//tr'/span>)
#創建空串列。
col=[]
i=0
#對于每一行,存盤每個第一元素(標題)和一個空串列。
for t in tr_elements[0] 。
i =1].
name=t.text_content()
# print '%d:"%s"'%(i,name)
col.append((name,[]))
#因為第一行是標題,所以資料被存盤在第二行開始。
for j in range(1,len(tr_elements))。
#T是我們的第j行。
T=tr_elements[j]
#I row is not of size 10, the //tr data is not from our table .
if len(T)! =6:
break。
#i是我們列的索引。
i=0
#Iterate through each element of the row
for t in T.iterchildren()。
data=t.text_content()
#檢查行是否為空。
if i>0:
#將任何數值轉換為整數。
try:
data=int(data)
except:
pass。
#Append the data to the empty list of the i'th column[/span].
col[i][1].append(data)
#Increment i for the next column[/span].
i =1。
Dict={title:column for (title,column) in col}。
df=pd.DataFrame(Dict)
df.head()
uj5u.com熱心網友回復:
你可以做到:
df["Date"] = pd.to_datetime(
df["Date"].str.replace(r"(d )([A-Z]. *)", r "1", regex=True)
)
print(df)
列印:
Date Open High Low Close Volume
0 2021-09-10 27.28 27.28 27.28 27.28 ----
1 2021-09-09 27.35 27.35 27.35 27.35 ----
2 2021-09-08 27.42 27.42 27.42 27.42 ----
3 2021-09-07 27.54 27.54 27.54 27.54 ----
4 2021-09-03 27.44 27.44 27.44 27.44 ----
5 2021-09-02 27.48 27.48 27.48 27.48 ----
6 2021-09-01 27.26 27.26 27.26 27.26 ----
7 2021-08-31 27.31 27.31 27.31 27.31 ----
8 2021-08-30 27.46 27.46 27.46 27.46 ----
9 2021-08-27 27.32 27.32 27.32 27.32 ----
10 2021-08-26 27.23 27.23 27.23 27.23 ----
11 2021-08-25 27.27 27.27 27.27 27.27 ----
12 2021-08-24 27.22 27.22 27.22 27.22 ----
13 2021-08-23 27.05 27.05 27.05 27.05 ----
14 2021-08-20 26.92 26.92 26.92 26.92 ----
15 2021-08-19 26.58 26.58 26.58 26.58 ----
16 2021-08-18 26.62 26.62 26.62 26.62 ----
17 2021-08-17 26.63 26.63 26.63 26.63 ----
18 2021-08-16 26.56 26.56 26.56 26.56 ----
19 2021-08-13 26.77 26.77 26.77 26.77 ----
20 2021-08-12 26.67 26.67 26.67 26.67 ----
uj5u.com熱心網友回復:
你可以像這樣將字串轉換為日期時間:
from datetime import datetime
d='September 10, 2021Fri, Sep 10, 2021'/span>
print(datetime.strptime(''.join(d. split(',')[-2:]), ' %b %d %Y')
輸出。2021-09-10 00:00:00
上面的不同步驟是:
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312007.html
標籤:

