这段代码的目的是
- 通过 Pandas 和 Beautiful Soup 抓取 300 个表
- 将这些表连接成一个数据框 该代码在第一步中运行良好。但它在第二个不起作用。
代码如下:
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/