【问题标题】:Collecting dictionaries from loop into a single data frame将循环中的字典收集到单个数据框中
【发布时间】:2021-09-02 18:32:56
【问题描述】:

您好,我有以下循环,它产生一个字典作为输出:

for l in soup.find_all('a'):
    link = (l.get('href'))
    if link.count('2021') == 1:
        stuff = urllib.parse.urlsplit(link)
        stuff = stuff.path.split('/')
        list(stuff)
        if stuff[1] == '2021':
            stuff = np.array(stuff)
            year = stuff[1]
            month = stuff[2]
            day = stuff[3]
            category = stuff[4]
            keywords = stuff[5:7]
            dict = {'year': year, 'month': month, 'day': day, 'category': category, 'keywords': keywords}

输出如下:

/Users/Programowanie/PycharmProjects/pythonProject1/venv/bin/python /Users/Programowanie/PycharmProjects/pythonProject1/main.py
   year month day category                               keywords
0  2021    09  02       us  supreme-court-texas-abortion-law.html
   year month day category                               keywords
0  2021    09  02       us  supreme-court-texas-abortion-law.html
   year month day category                               keywords
0  2021    09  02       us  supreme-court-texas-abortion-law.html
   year month day category                       keywords
0  2021    09  02       us                       politics
1  2021    09  02       us  biden-abortion-texas-law.html
   year month day category                       keywords
0  2021    09  02       us                       politics
1  2021    09  02       us  biden-abortion-texas-law.html

我想将所有单独的字典排序到一个单独的 DataFrame 中,以便将年、月、日、类别、关键字的值保存在相应的年、月、日、类别、关键字列中。你知道怎么做吗?

提前致谢

【问题讨论】:

  • pd.concat(output) 假设 output 是您的字典列表。

标签: python pandas web-scraping


【解决方案1】:

我建议您初始化一个空的pd.DataFrame,并在每次迭代时将值附加到这个表达式df.loc[len(df)] = dict_

这个例子: (应该按原样工作)

dict_ = {
    'year': '2021',
    'month': '09',
    'day': '02',
    'category': 'us',
    'keywords': 'supreme-court-texas-abortion-law.html'
}

df = pd.DataFrame(columns=['year', 'month', 'day', 'category','keywords'])
for x in range(10):
    df.loc[len(df)] = dict_

print(df)

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 2017-10-12
    • 2015-10-31
    • 2021-02-10
    • 2019-04-24
    • 2012-04-10
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多