在 for 循环中连接数据帧

ALE*_* W. 2 python pandas

我写了一个类来抓取公共假期数据,但我想用很多年迭代我的类,例如:

outputt_path = "C:/Users/N000193384/Downloads/countries/"
recent_years = ["2015", "2016", "2017", "2018"]
for year in recent_years : 
    PBC = Event_Scraper("italy", year, outputt_path)
    df = PBC._read_html_()
    df = df.append(df)
Run Code Online (Sandbox Code Playgroud)

我的课程采用了国家/地区的名称和年份,outputt_path 在那里毫无用处。

_read_html_() 构建一个清理后的数据帧,我想附加每个数据帧。

这是一年的数据框示例:

    Date    Holiday Name    Holiday Type
0   2018-01-01  New Year's Day  National holiday
1   2018-01-06  Epiphany    National holiday
2   2018-03-20  March Equinox   Season
3   2018-03-30  Good Friday Observance
4   2018-04-01  Easter Day  National holiday
Run Code Online (Sandbox Code Playgroud)

Abh*_*yay 6

您可以创建一个数据帧列表,并不断将每年数据的新数据帧附加到该列表中。完成数据抓取后,您可以将它们连接到一个数据帧中,如下所示:

dfs = []
for year in recent_years : 
    PBC = Event_Scraper("italy", year, outputt_path)
    df = PBC._read_html_()
    dfs.append(df)

final_df = pd.concat(dfs)
Run Code Online (Sandbox Code Playgroud)

在数据帧上追加或执行 concat 是一项昂贵的操作,因为 Pandas 需要为新数据帧分配内存并复制所有数据,因此在循环中多次执行此操作将非常昂贵。这样做可以节省开销,因为您只需执行一次。