大熊猫合并300个数据框

时间:2018-09-21 09:44:11

标签: python pandas beautifulsoup

此代码的目的是

  1. 通过熊猫和美丽汤刮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行,位于初始

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

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

的对象

1 个答案:

答案 0 :(得分:3)

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 的列表,作为在站点中进行迭代时追加DataFrame的位置。然后,将 dfs 作为参数传递给concat。