【问题标题】:Pandas - read_html with index_col not intended output when doing to_htmlPandas - 执行 to_html 时带有 index_col 的 read_html 不是预期输出
【发布时间】:2022-01-08 09:11:07
【问题描述】:

我可能只是不完全理解 pandas,但在使用 read_html() 并设置了 index_col 标志、修改数据框,然后尝试再次使用 to_html() 时,我遇到了一些意外行为。

这就是我的意思。我有这个 HTML 文件:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>index</th>
      <th>Avg</th>
      <th>Min</th>
      <th>Max</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>build1</td>
      <td>55.102323</td>
      <td>37.101219</td>
      <td>60.7</td>
    </tr>
  </tbody>
</table>

然后我使用 pandas read_html 如下:

dataFrameList = pd.read_html('empty.html', index_col=0)
df = dataFrameList[0]

这会产生如下数据框:

              Avg        Min   Max
index                             
build1  55.102323  37.101219  60.7

然后我有一小段测试代码如下所示:

df.drop(['build1'], inplace=True)
df.loc['build2'] = [121212, 12443, 1290120]
print(df.to_html())

我得到以下输出:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Avg</th>
      <th>Min</th>
      <th>Max</th>
    </tr>
    <tr>
      <th>index</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>build2</th>
      <td>121212.0</td>
      <td>12443.0</td>
      <td>1290120.0</td>
    </tr>
  </tbody>
</table>

我做错了什么?我试图将标志 to_html(.., index=False) 设置为关闭,但这摆脱了构建名称(我需要)。

我想要的输出(只是为了清楚)如下:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>index</th>
      <th>Avg</th>
      <th>Min</th>
      <th>Max</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>build2</th>
      <td>121212.0</td>
      <td>12443.0</td>
      <td>1290120.0</td>
    </tr>
  </tbody>
</table>

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    有一个解决方法:

    df.insert(0, 'index', df.index)
    print(df.to_html(index=False))
    

    这会产生所需的输出(除了第二行中的&lt;th&gt;,我猜这是一个错字?)。

    【讨论】:

    • 这很好用,但如果你能添加解释,我将非常感激。
    • to_html 函数用于渲染表格。尝试在 jupyter notebook 中输出表格,你会看到确实有两个表头,一个是列,第二个是索引(你可以有 MultiIndex)。我在上面所做的只是在位置 0 处创建一个名为 index 的假列,并将索引中的数据复制到其中。然后我们只是将它输出到没有实际索引的html中。
    • 是的,如果您查看它输出的表格和上面的 text 输出,它们看起来都相似(第 0 行的列,'index' 作为标题第 1 行的索引,实际的索引行从第 2 行开始)。
    • @noisefield:整洁,请将问题的解释编辑到您的答案中(然后它会被编入索引并且是可搜索的,与 cmets 不同,并且不容易暂时消失)。
    • (这是 2017 年特定版本的错误吗?(哪些版本?)现在修复了吗?这在当前版本中有效吗?等等)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2018-04-23
    • 2022-08-15
    • 2015-02-28
    相关资源
    最近更新 更多