熊猫用for循环连接数据帧

时间:2019-01-28 03:03:10

标签: python python-3.x pandas for-loop web-scraping

我正在尝试从网站获取表格。该网站的URL包含日期,因此我必须遍历日期才能获取历史数据。我生成的日期如下:

import datetime

start = datetime.datetime.strptime("26-09-2016", "%d-%m-%Y")
end = datetime.datetime.strptime("30-09-2016", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

dates_list = []
for date in date_generated:
    txt = str(str(date.day) + '.' + str(date.month) + '.' + str(date.year))
    dates_list.append(txt)

dates_list

此后,我运行下面的代码来连接所有表:

for i in range(0, 3):
    allURL = 'https://www.uzse.uz/trade_results?date=' + dates_list[i] + '&locale=en&mkt_id=ALL&page=%d'

    ndf_list = []
    for i in range(1, 100):
        url = allURL %i
        if pd.read_html(url)[0].empty:
            break
        else :
            ndf_list.append(pd.read_html(url)[0])

    ndf = pd.concat(ndf_list)
    ndf.insert(0, 'Date', dates_list[i])

mdf = pd.concat(ndf, ignore_index = True)
mdf

但是,这不起作用,我得到了:

TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"

我不明白我在做什么错。我预计将从9月26日,27日和28日开始提供一张桌子。

请帮助。

1 个答案:

答案 0 :(得分:1)

不确定最后一行,但是我会这样处理

import datetime
import pandas as pd

start = datetime.datetime.strptime("26-09-2016", "%d-%m-%Y")
end = datetime.datetime.strptime("30-09-2016", "%d-%m-%Y")
date_generated = [
    start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

dates_list = []
for date in date_generated:
    txt = str(str(date.day) + '.' + str(date.month) + '.' + str(date.year))
    dates_list.append(txt)

dates_list

ndf = pd.DataFrame()  # create empty ndf
for i in range(0, 3):
    allURL = 'https://www.uzse.uz/trade_results?date=' + \
        dates_list[i] + '&locale=en&mkt_id=ALL&page=%d'

    # ndf_list = []
    for j in range(1, 100):
        url = allURL % j
        if pd.read_html(url)[0].empty:
            break
        else:
            # ndf_list.append(pd.read_html(url)[0])
            chunk = pd.read_html(url)[0]
            chunk['Date'] = dates_list[i] # Date is positioned at last position, let's fix that
            # get a list of all the columns
            cols = chunk.columns.tolist()
            # rearrange the columns, move the last element (Date) to the first position
            cols = cols[-1:] + cols[:-1]
            # reorder the dataframe
            chunk = chunk[cols]
            ndf = pd.concat([ndf, chunk])

    # ndf = pd.concat(ndf_list)

# ndf.insert(0, 'Date', dates_list[i])

print(ndf)
# mdf = pd.concat(ndf, ignore_index=True)
# mdf