繁体   English   中英

嵌套嵌套的熊猫在创建的不同数据帧上插入多个数据

[英]Pandas nested for loop insert multiple data on different data frames created

我是数据科学的新手,目前正在练习以提高自己的技能。 我使用了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

它返回的是:不同的数据帧,但仅适用于最后一个大陆

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

当前,您正在使用每个循环覆盖年份索引,因此仅保留具有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避免嵌套的for循环,然后melt数据以进行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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM