如何将wikipediawikitable转换为Python Pandas数据帧?

2024-05-13 03:52:15 发布

您现在位置:Python中文网/ 问答频道 /正文

在维基百科中,你可以找到一些有趣的数据进行排序、过滤。。。在

这是一个wikitable的示例

{| class="wikitable sortable"
|-
! Model !! Mhash/s !! Mhash/J !! Watts !! Clock !! SP !! Comment
|-
| ION || 1.8 || 0.067 || 27 ||  || 16 || poclbm;  power consumption incl. CPU
|-
| 8200 mGPU || 1.2 || || || 1200 || 16 || 128 MB shared memory, "poclbm -w 128 -f 0"
|-
| 8400 GS || 2.3 || || ||  ||  || "poclbm -w 128"
|-
|}

我正在寻找一种方法将这些数据导入到Python Pandas数据帧


Tags: 数据示例model排序commentspclasspower
3条回答

你可以直接用熊猫。像这样。。。在

pandas.read_html(url, attrs={"class": "wikitable"})

下面是一个解决方案,使用py-wikimarkupPyQuery从wikimarkup字符串中提取所有表作为pandas数据帧,忽略非表内容。在

import wikimarkup
import pandas as pd
from pyquery import PyQuery

def get_tables(wiki):
    html = PyQuery(wikimarkup.parse(wiki))
    frames = []
    for table in html('table'):
        data = [[x.text.strip() for x in row]
                for row in table.getchildren()]
        df = pd.DataFrame(data[1:], columns=data[0])
        frames.append(df)
    return frames

给出以下输入

^{pr2}$

get_tables返回以下数据帧。在

       Model Mhash/s Mhash/J Watts Clock  SP                                     Comment
0        ION     1.8   0.067    27        16        poclbm;  power consumption incl. CPU
1  8200 mGPU     1.2                1200  16  128 MB shared memory, "poclbm -w 128 -f 0"
2    8400 GS     2.3                                                     "poclbm -w 128"

   A  B  C
0  0  1  2
1  3  4  5

{{cd2>然后使用^{cd2}进行预处理:

table = """{| class="wikitable sortable"
|-
! Model !! Mhash/s !! Mhash/J !! Watts !! Clock !! SP !! Comment
|-
| ION || 1.8 || 0.067 || 27 ||  || 16 || poclbm;  power consumption incl. CPU
|-
| 8200 mGPU || 1.2 || || || 1200 || 16 || 128 MB shared memory, "poclbm -w 128 -f 0"
|-
| 8400 GS || 2.3 || || ||  ||  || "poclbm -w 128"
|-
|}"""

data = StringIO(re.sub("^\|.|^!.", "", table.replace("|-\n", ""), flags=re.MULTILINE))
df = pd.read_csv(data, delimiter="\|\||!!", skiprows=1)

输出:

^{pr2}$

相关问题 更多 >