python - Pandas 合并 300 个数据帧

标签 python pandas beautifulsoup

这段代码的目的是

  1. 通过 Pandas 和 Beautiful Soup 抓取 300 个表
  2. 将这些表连接成一个数据框 该代码在第一步中运行良好。但它在第二个不起作用。

代码如下:

import pandas as pd
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup


header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 " "Safari/537.36", "X-Requested-With": "XMLHttpRequest"}
url = open(r"C:\Users\Sayed\Desktop\script\links.txt").readlines()

for site in url:
    req = Request(site, headers=header)
    page = urlopen(req)
    soup = BeautifulSoup(page, 'lxml')

    table = soup.find('table')
    df = pd.read_html(str(table), parse_dates={'DateTime': ['Release Date', 'Time']}, index_col=[0])[0]
    df = pd.concat(df, axis=1, join='outer').sort_index(ascending=False)
    print(df)

这里是错误:

追溯(最近的调用最后):

文件“D:/Projects/Tutorial/try.py”,第 18 行,在

df = pd.concat(df, axis=1, join='outer').sort_index(ascending=False)

文件“C:\Users\Sayed\Anaconda3\lib\site-packages\pandas\core\reshape\concat.py”,第 225 行,concat 复制=复制,排序=排序)

文件“C:\Users\Sayed\Anaconda3\lib\site-packages\pandas\core\reshape\concat.py”,第 241 行,在 init

'"{name}"'.format(name=type(objs).__name__))

TypeError: 第一个参数必须是 pandas 对象的可迭代对象,你传递了一个类型为“DataFrame”的对象

最佳答案

Pandas concat 函数将 Series、DataFrame 或 Panel 对象的序列或映射作为第一个参数。您的代码当前正在传递单个 DataFrame。

我怀疑以下方法可以解决您的问题:

import pandas as pd
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup


header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 " "Safari/537.36", "X-Requested-With": "XMLHttpRequest"}
url = open(r"C:\Users\Sayed\Desktop\script\links.txt").readlines()

dfs = []

for site in url:
    req = Request(site, headers=header)
    page = urlopen(req)
    soup = BeautifulSoup(page, 'lxml')

    table = soup.find('table')
    df = pd.read_html(str(table), parse_dates={'DateTime': ['Release Date', 'Time']}, index_col=[0])[0]
    dataframes.append(df)

concat_df = pd.concat(dfs, axis=1, join='outer').sort_index(ascending=False)
print(df)

我所做的只是创建一个名为 dfs 的列表,作为在您遍历站点时附加数据帧的位置。然后 dfs 作为参数传递给 concat。

关于python - Pandas 合并 300 个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440927/

相关文章:

python - Pandas DataFrame 列到数据透视表中的单元格

pandas - 使用groupby在大型数据帧上有效地进行Fillna(正向填充)?

python - BS4 Python : Trying to take page links from Google but the URLs I get are all the same

Python BeautifulSoup 解析

python - 在 Mac 上安装适用于 python 的 WEKA

python - 如何将 DataFrame 列的非空条目合并到一个新列中?

python - 继续基于错误的 Python 脚本

python - 创建函数来使用 pandas 列的最大值进行计算

python - 检查 BeautifulSoup 3 中的元素类型

停止和等待算法的 Python 实现