在Pandas的資料框中,有沒有一種方法可以透過連結來提取正規表示式模式?
P粉770375450
P粉770375450 2023-08-16 20:25:57
0
1
489
<p>我正在嘗試從生成的Pandas表中的連結中提取正規表示式模式。 </p> <p>產生Pandas資料框的程式碼如下:</p> <pre class="brush:php;toolbar:false;">import pandas as pd import re url = 'https://www.espncricinfo.com/records/year/team-match-results/2005-2005/twenty20-internationals-3' base_url = 'https://www.espncricinfo.com' table = pd.read_html(url, extract_links = "body")[0] table = table.apply(lambda col: [link[0] if link[1] is None else f'{base_url}{link[1]}' for link in col]) table</pre> <p>我想從表格中的連結中提取比賽ID。對於每場比賽,比賽ID是在“t20i-”模式之後連續的數字集合,並在斜杠之前結束。例如: 對於這場比賽,比賽ID是211048。以下是單場比賽的代碼:</p> <pre class="brush:php;toolbar:false;">scorecard_url = 'https://www.espncricinfo.com/series/australia-tour-of-new-zealand-2004-05-61407/new- zealand-vs-australia-only-t20i-211048/full-scorecard' match_id = re.findall('t20i-(d*)/', scorecard_url) match_id[0]</pre> <p>我想透過使用一個派生列match-id來對整個表格進行操作。該列使用Scorecard列。然而,我一直無法實現。 </p> <p>我最初嘗試了這個簡單的指令:</p> <pre class="brush:php;toolbar:false;">table['match_id']= re.findall('t20i-(d*)/', table['Scorecard']) table</pre> <p>我得到了一個'TypeError: expected string or bytes-like object'的錯誤,這讓我認為鏈接沒有存儲為字符串,可能是導致問題的原因。 </p> <p>然後我試了:</p> <pre class="brush:php;toolbar:false;">table['match_id']= re.findall('t20i-(d*)/', str(table['Scorecard'])) table</pre> <p>這給了我一個'ValueError: Length of values (0) does not match length of index (3)'的錯誤,我不確定這是什麼原因。 </p> <p>我還嘗試了使用lambda函數的方法,但沒有成功。如果這個方法可行,我也不介意使用它。 </p>
P粉770375450
P粉770375450

全部回覆(1)
P粉310931198

你接近了。這將新增一個帶有比賽ID的新欄位。

import pandas as pd
import re

url = 'https://www.espncricinfo.com/records/year/team-match-results/2005-2005/twenty20-internationals-3'
base_url = 'https://www.espncricinfo.com'

def match(row):
    match_id = re.findall('t20i-(\d*)/', row[1])
    return match_id[0]
    
table = pd.read_html(url, extract_links = "body")[0]
table['match'] = table['Scorecard'].apply(match)
print(table)

輸出:

Team 1  ...   match
0   (新西兰, None)  ...  211048
1       (英格兰, None)  ...  211028
2  (南非, None)  ...  222678

[3 行 x 8 列]
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!