【发布时间】:2016-04-24 13:59:54
【问题描述】:
我有以下数据:
url='https://raw.githubusercontent.com/108michael/ms_thesis/master/clean_gdp_data_all.csv'
c=pd.read_csv(url, index_col=0)
c = c.loc[(c.GeoName == 'California') & \
(c.ComponentName == 'Real GDP by state')]
c.head(3)
GeoName ComponentName IndustryClassification Description 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
38281 California Real GDP by state 111-112 Farms 15717 18751 18215 15335 14109 18798 19197 16535 15014 16909 0
38282 California Real GDP by state 113-115 Forestry, fishing, and related activities 6234 6278 7845 7786 7365 7390 7831 8115 8995 9312 0
38284 California Real GDP by state 211 Oil and gas extraction 7769 8107 10693 12342 12010 17155 14575 15289 18849 16165 0
我想用 for 循环运行以下代码,但我想每年(2004-2014)都运行它,然后将它们合并在一起,如最后一行代码所示:
d = c.sort_values('2004', ascending=False).head(10)[['GeoName', \
'IndustryClassification', 'Description', 'ComponentName', '2004' ]]
e = c.sort_values('2005', ascending=False).head(10)[['GeoName', \
'IndustryClassification', 'Description', 'ComponentName', '2005' ]]
crgdp = pd.merge(d,e, how='inner', on=['GeoName', \
'IndustryClassification', 'Description', 'ComponentName'])
【问题讨论】:
-
为什么您对数据框的引用不断在
c和d之间切换? -
@brittenb:感谢您的评论。我刚刚更新了代码。
-
@MaxU:感谢您的评论!是的,我可以这样做。这个问题有点复杂,我需要为每个
GeoName和每个ComponentName执行此合并。我每年都单独排序,因为我需要每年排名前 10 的行业。我可以每年将数据分类为 11 个不同的 dfs。我还可以将raw-file拆分为GeoName和ComponentName。但是,我不知道如何用 pandas 很好地做到这一点。 -
@MaxU:我选择设置一个模板来收集每个
ComponentName的所有状态/年份,然后切换出ComponentName;但是,我稍后会将我的所有代码清理到项目中。现在我把结果放在口才上。已经2个多月了,我仍在努力处理我的数据。我还有不到 4 个月的时间。