11

ウィキペディアでは、並べ替え、フィルター処理などを行う興味深いデータを見つけることができます。

これはウィキテーブルのサンプルです

{| 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 DataFrame にインポートする方法を探しています

4

4 に答える 4

13

py-wikimarkupPyQueryを使用して、すべてのテーブルを wikimarkup 文字列から pandas DataFrames として抽出し、テーブル以外のコンテンツを無視するソリューションを次に示します。

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

次の入力を考えると、

wiki = """
=Title=

Description.

{| 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"
|-
|}

{| class="wikitable sortable"
|-
! A !! B !! C
|-
| 0
| 1
| 2
|-
| 3
| 4
| 5
|}
"""

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
于 2013-03-31T04:04:52.340 に答える
1

編集済み - 以下の完全な回答。パンダがインストールされていないので、うまくいくかどうか教えてください。

from pandas import *

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"
|-
|}'''
rows = wikitable.split('|-')
header = []
table = []
for i in rows:
     line = i.strip()
     if line.startswith('!'):
         header = line.split('!!')
     elif line.startswith('|') and line.strip() != '|}':
         table.append(line[2:].split('||'))

data = {}
for i in range(len(header) - 1):
    col = []
    for row in table:
        col.append(row[i])
    data[header[i]] = col

print(data)

df = DataFrame(data)
于 2013-03-30T23:24:38.060 に答える