如何用Pandas读取HTML表格后扁平化数据并提取指定列链接?
问题
现有如下HTML表格:
html_text = "<table> <tr> <th>Home</th> <th>Score</th> <th>Away</th> <th>Report</th> </tr> <tr> <td>Arsenal</td> <td></td> <td>Manchester Utd</td> <td></td> </tr> <tr> <td>Everton</td> <td>2-0</td> <td>Liverpool</td> <td><a href="/asdasdasd/">Match Report</a></td> </tr> </table>"
用requests获取后,通过下面的Pandas代码转成数据集:
matches = pd.read_html(StringIO(str(html_text)), extract_links="all")[0]
得到的数据里每个元素都是(文本, 链接)的元组,格式如下:
(Home, None),(Score, None),(Away, None),(Report, None) (Arsenal, None),(NaN, None),(Manchester Utd, None),(NaN, None) (Everton, None),(2-0, None),(Liverpool, None),(Match Report, /asdasdasd/)
现在要把数据集扁平化:其他列保留文本,只让Report列保留链接,最终得到这样的格式:
Home, Score, Away, Report Arsenal, NaN, Manchester Utd, NaN Everton, 2-0, Liverpool, /asdasdasd/
最简单的处理方法
直接对DataFrame的列做针对性处理就行:
# 处理Home、Score、Away列,取元组里的文本部分 matches[['Home', 'Score', 'Away']] = matches[['Home', 'Score', 'Away']].applymap(lambda x: x[0]) # 处理Report列,取元组里的链接部分 matches['Report'] = matches['Report'].apply(lambda x: x[1])
嫌写列名麻烦的话,也可以遍历所有列,根据列名判断处理逻辑:
for col in matches.columns: matches[col] = matches[col].apply(lambda x: x[1] if col == 'Report' else x[0])
执行完上面的代码,就能得到你想要的数据集格式了。
内容的提问来源于stack exchange,提问作者Ewan
相关产品推荐
相关产品推荐

