【问题标题】:pandas read_html function with colspan=2带有 colspan=2 的 pandas read_html 函数
【发布时间】:2013-11-05 14:38:57
【问题描述】:

我正在使用 pandas read_html 函数将 html 表加载到数据帧中,但是它失败了,因为 source data 有一个 colspan=2 合并标题,导致这个 AssertionError: 6 columns passed, pass data has 7 columns .

我已经尝试了使用 header kwarg (header=None, header=['Code'...]) 的各种选项,但似乎没有任何效果。

有没有人知道使用 pandas read_html 解析和 html 表格与合并列的任何方法?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果你不坚持使用 pandas 中的 read_html,那么这段代码就可以了:

    import pandas as pd
    from lxml.html import parse
    from urllib2 import urlopen
    from pandas.io.parsers import TextParser
    
    def _unpack(row, kind='td'):
       elts = row.findall('.//%s' % kind)
       return [val.text_content() for val in elts]
    
    def parse_options_data(table):
      rows = table.findall('.//tr')
      header = _unpack(rows[0], kind='th')
      data = [_unpack(r) for r in rows[1:]]
      return TextParser(data, names=header).get_chunk()
    
    parsed = parse(urlopen('http://www.bmfbovespa.com.br/en-us/intros/Limits-and-Haircuts-for-accepting-stocks-as-collateral.aspx?idioma=en-us'))
    doc = parsed.getroot()
    tables = doc.findall('.//table')
    table = parse_options_data(tables[0])
    

    本文摘自 Wes McKinney 的“Python for Data analysis”一书。

    【讨论】:

    • 谢谢马丁...我想我从所有这些很棒的库中变得懒惰了;)
    【解决方案2】:

    pandas >= 0.24.0 理解 colspanrowspan 属性。根据the release notes

    result = pd.read_html("""
        <table>
          <thead>
            <tr>
              <th>A</th><th>B</th><th>C</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td colspan="2">1</td><td>2</td>
            </tr>
          </tbody>
        </table>""")
    
    result
    

    输出:

    [   A  B  C
     0  1  1  2
    

    以前这会返回以下内容:

    [   A  B   C
     0  1  2 NaN]
    

    由于找不到 URL,我无法使用您的链接进行测试。

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2020-12-29
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 2017-02-10
      • 2017-05-17
      相关资源
      最近更新 更多