【问题标题】:Extraction of date from first two columns of a table using BeautifulSoup and arranging them in Pandas dataframe without duplicates使用 BeautifulSoup 从表的前两列中提取日期并将它们排列在 Pandas 数据框中,没有重复
【发布时间】:2022-01-19 20:41:29
【问题描述】:

这是我之前的问题Extraction of tds from table using BeautifulSoup and arranging them in Pandas dataframe together with the table id的后续问题

我在解决方案中遇到了异常行为:

  1. 由于存在第三列而导致空行条目,遗憾的是我在上述问题中没有提及它
  2. 在我的上述问题中创建的 Pandas 数据框中出现重复记录

我提取了以下 html 代码:

<table id=table1>

  <thead>
    <tr class="table_columns">
      <th id="header1">
        "Column 1 Title"
      </th>
      <th id="header2">
        "Column 2 Title"
      </th>
      <th id="header3">
        <span></span>
      </th>
    </tr>
  </thead>
  
  <tbody>
    <tr class="evenRow">
      <td headers="_header1">firstrowcolumn1data</td>
      <td headers="_header2">firstrowcolumn2data</td>
      <td headers="_header3">
        <a>
          <img src="image1">
        </a>
      </td>
    </tr>
    <tr class="oddRow">
      <td headers="_header1">secondrowcolumn1data</td>
      <td headers="_header2">secondrowcolumn2data</td>
      <td headers="_header3">
        <a>
          <img src="image1">
        </a>
    </tr>
  </tbody>
</table>

我需要提取表(table1)的表数据和id,然后将它们排列成一个Pandas数据框,类似这样:

id table data
table1 firstrowcolumn1data
table1 firstrowcolumn2data
table1 secondrowcolumn1data
table1 secondrowcolumn2data

我已经实施了针对我之前的问题给出的以下解决方案:

data = []
for table in s.find_all('table'):
    for td in table.find_all('td'):
        data.append((table.get('id'), td.text))
df = pd.DataFrame(data, columns=['id', 'table data'])

但是,我的输出如下:

id table data
None firstrowcolumn1data
None firstrowcolumn2data
None
None secondrowcolumn1data
None secondrowcolumn2data
None
table1 firstrowcolumn1data
table1 firstrowcolumn2data
table1
table1 secondrowcolumn1data
table1 secondrowcolumn2data
table1

请指教。

【问题讨论】:

  • 我无法重现相同的错误数据帧。我通过运行您的代码得到的 datframe 看起来就像您预期的那样,有几行以 \n\n\n\n\n 作为内容。
  • 您确定您提供的 HTML 与您使用的相同吗?
  • @user17242583 我不能在这里展示整个代码,因为它太复杂了。鉴于我面临的其他挑战,我愿意接受以“无”为 id 的重复项

标签: pandas beautifulsoup html-table


【解决方案1】:

试试这个:

df = df.assign(**{'table data': df['table data'].str.replace(r'^\s+$', '', regex=True)}).replace({None:np.nan,'':np.nan,'None':np.nan}).dropna()

输出:

>>> df
        id            table-data
6   table1  firstrowcolumn1data 
7   table1  firstrowcolumn2data 
9   table1  secondrowcolumn1data
10  table1  secondrowcolumn2data

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2022-01-03
    • 2018-11-13
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多