【问题标题】:How do I concat dataframes with a for loop in Python & Pandas如何在 Python 和 Pandas 中使用 for 循环连接数据帧
【发布时间】:2020-05-08 19:47:39
【问题描述】:

我有一本数据帧字典(248 个国家/地区),我想将其合并到一个数据帧中。

数据框称为 dfs,所以如果我想访问阿尔巴尼亚的内容,我使用:

dfs["Albania"]

我之前在学习如何合并数据帧时使用以下代码对 4 个数据帧执行此操作。

我是否可以将其调整为与我现在想要包含的 248 个国家/地区的循环,并将每个连接的 df 的键设置为国家/地区名称?

在过去的几个小时里,我在这方面进展甚微!

datasets = [df_ireland, df_italy, df_france, df_germany]

frames = []

for frame in datasets:
    frames.append(frame)

df_join = pd.concat(frames, keys=['Ireland', 'Italy', 'France', 'Germany'])

这是我用来构建字典的循环,以防万一:

# Import the libraries
import requests
import requests_cache

import json

import pandas as pd
import numpy as np
from pandas import Series, DataFrame, json_normalize

from datetime import datetime

# Make an API call and store the response.
sum_url = 'https://api.covid19api.com/summary'
sum_data = requests.get(sum_url)

# Store the API response in a variable.
available_sum_data = sum_data.json()
sum_df = json_normalize(available_sum_data["Countries"])

# Make a list of countries
countries = sum_df['Country'].tolist()

# Make a empty dictionary to hold dataframes
dfs = {}


for country in countries:
    print(country)

    try:
        # check the cache and if old data call api
        requests_cache.install_cache(f'{country} cache', expire_after=21600)
        url = f'https://api.covid19api.com/total/dayone/country/{country}'
        data = requests.get(url)

        # test if cache used
        print(data.from_cache)

    except requests.exceptions.RequestException as e:  # This is the correct syntax
        print(e)
        print('cant print' + country)

    try:
        available_data = data.json()
        dfs[f'{country}'] = pd.json_normalize(available_data)


        # Create Daily new cases column & SMA
        dfs[f'{country}']["New Cases"] = dfs[f'{country}']['Confirmed'].diff()
        dfs[f'{country}']["SMA_10 New Cases"] = dfs[f'{country}']["New Cases"].rolling(window=10).mean()

        # Create Daily new deaths column & SMA
        dfs[f'{country}']["New Deaths"] = dfs[f'{country}']['Deaths'].diff()
        dfs[f'{country}']["SMA_10 New Deaths"] = dfs[f'{country}']["New Deaths"].rolling(window=10).mean()


    except:
        print('cant format to json: ' + country)

【问题讨论】:

    标签: python pandas dataframe dictionary concatenation


    【解决方案1】:

    我认为您已经拥有出色的字典 dfs,因此您无需执行循环。你能试试这个吗?

    df_joined = pd.concat(dfs.values(), keys=dfs.keys())
    

    【讨论】:

    • 哇。那是完全完美的。谢谢
    猜你喜欢
    • 2019-06-21
    • 2019-07-17
    • 2022-01-23
    • 2022-09-23
    • 2020-08-14
    • 2019-05-12
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多