python – 嵌套for循环的Pandas在创建的不同数据帧上插入多个数据

我是数据科学的新手,我目前正在练习提高自己的技能.我使用了来自kaggle的数据集,并计划如何呈现数据并遇到问题.

我想要实现的是使用for循环将数据插入到不同的数据帧.我已经看到了这个例子,并使用字典保存数据帧,但数据帧上的数据被覆盖.

我有一个数据框列表:

continents_list = [african_countries, asian_countries, european_countries, north_american_countries,
          south_american_countries, oceanian_countries]

这是来自其中一个大洲的数据框的示例:

    Continent   Country Name   Country Code    2010    2011    2012    2013    2014
7    Oceania      Australia         AUS        11.4    11.4    11.7    12.2    13.1
63   Oceania         Fiji           FJI        20.1    20.1    20.2    19.6    18.6
149  Oceania     New Zealand        NZL        17.0    17.2    17.7    15.8    14.6
157  Oceania   Papua New Guinea     PNG         5.4     5.3     5.4     5.5     5.4
174  Oceania   Solomon Islands      SLB         9.1     8.9     9.3     9.4     9.5

我首先选择了一年中率最高的国家的整行:

def select_highest_rate(continent, year):
    highest_rate_idx = continent[year].idxmax()
    return continent.loc[highest_rate_idx]

然后创建一个for循环,为每个单独的年份创建不同的数据框,这些数据框必须包含该年度的所有大陆及其相应的国家和费率:

def show_highest_countries(continents_list):
    df_highest_countries = {}
    years_list = ['2010','2011','2012','2013','2014']
    for continent in continents_list:
        for year in years_list:
            highest_country = select_highest_rate(continent, year)
            highest_countries = highest_country[['Continent','Country Name',year]]
            df_highest_countries[year] = pd.DataFrame(highest_countries)
    return df_highest_countries

here is what it returns: different data frames but only for the last continent

问题:如何将所有数据(大陆)保存在同一数据框中?字典不可能吗?

最佳答案 目前,您使用每个循环覆盖年份索引,因此只有2010-2014年的最后一个大陆数据框仍然存在:

df_highest_countries[year] = pd.DataFrame(highest_countries)

您可以为一个更独特的字典键添加大陆,然后连接到一个最终的数据帧:

df_highest_countries[continent+str(year)] = pd.DataFrame(highest_countries)

finaldf = pd.concat(df_highest_countries, join='outer').reset_index(drop=True)

或者,考虑通过在开始时将所有连接在一起来避免嵌套for循环,然后将数据融合为groupby聚合.然后,仅保留每年和每个大陆具有此类最大值的国家/地区记录.如果需要,您可以使用pivot_table回溯到年份列.

df = pd.concat(continents_list)

# MELT FOR YEAR VALUES IN COLUMN
df = pd.melt(df, id_vars=['Continent', 'Country Name', 'Country Code'], var_name='Year')

# AGGREGATE HIGHEST VALUE AND MERGE BACK TO ORIGINAL SET
df = df.groupby(['Continent', 'Year'])['value'].max().reset_index().\
        merge(df, on=['Continent', 'Year', 'value'])

# PIVOT BACK TO YEAR COLUMNS
pvt = df.pivot_table(index=['Continent', 'Country Name', 'Country Code'],
                     columns='Year', values='value').reset_index()
点赞