【发布时间】:2017-08-31 01:09:59
【问题描述】:
我是数据科学的新手,我目前正在练习以提高我的技能。我使用了来自 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
问题:如何将所有数据(大陆)保存在同一个数据框中?用字典不行吗?
【问题讨论】:
标签: python pandas dataframe nested-loops data-science