首页 > 解决方案 > 如何修复被拉入 Python DataFrame 的维基百科表格

问题描述

我有一个脚本,它使用 Beautiful Soup 从指定的文章中提取 Wikipedia 表,然后将该表插入到 Python DataFrame 中。问题来自 Wikipedia 的格式,其中 HTMl 不会在每一行上返回共享值,因此当两个连续的行在一列中具有相同的值时,它只返回第一个实例。

结果是类似于下面的输出。

       Date        |   Random Field   |   State   |   Random Field   |   Source 
Friday, June 1st   |       text       |     WY    |       text       |    [12] 
      text         |       text       |    [13]   |       NaN        |    NaN
Friday, June 8th   |       text       |     VT    |       text       |    [14] 
      text         |        CA        |    text   |       [15]       |    NaN

在第二行中,该条目共享日期和状态,最后产生两个 NaN 值。在第四行中,该条目仅共享一个日期值。

目标是遍历 DataFrame 查找不符合预期的 Date 和 State 值(即不是 Dayofweek、Month # for date 或 XY for state),当发现异常时,从上面复制值并将单元格适当地移动到返回如下输出。

       Date        |   Random Field   |   State   |   Random Field   |   Source 
Friday, June 1st   |       text       |     WY    |       text       |    [12] 
Friday, June 1st   |       text       |     WY    |       text       |    [13]
Friday, June 8th   |       text       |     VT    |       text       |    [14] 
Friday, June 8th   |       text       |     CA    |       text       |    [15]

我不确定这是否可能,更不用说高效了。我知道我可以在 Excel 中做到这一点,但更愿意留在 Python 中,以便在可能需要更多表时构建处理管道。

非常感谢您的任何指导!

编辑:根据下面的请求添加 DataFrame 如何制作的详细信息,以防万一。

with io.open('Wiki article', "w", encoding="utf-8") as f:
    f.write(article)

for caption in soup.find_all('caption'):
    if "CAPTION TEXT" in caption.get_text():
        ths = table.find_all('th')
        headings = [th.text.strip() for th in ths]
        table = caption.find_parent('table')

df = pd.read_html(str(table))
df = pd.DataFrame(df[0])

标签: pythonpandasdataframewikipedia

解决方案


推荐阅读