2

我正在写一篇经济学论文,需要一些帮助来组合和转换两个数据集。

我有两个熊猫数据框,一个带有国家列表及其邻国(borderdf),例如

borderdf
country    neighbor
sweden     norway
sweden     denmark
denmark    germany
denmark    sweden

一个带有每个国家和年份的数据(datadf),例如

datadf
country    gdp    year
sweden     5454   2004
sweden     5676   2005
norway     3433   2004
norway     3433   2005
denmark    2132   2004
denmark    2342   2005

我需要在 datadf 中为 neighbormeangdp 创建一个列,该列将包含所有邻居的 gdp 的平均值,由 neighbordf 给出。我希望我的结果看起来像这样:

datadf
country    year    gdp    neighborsmeangdp
sweden     2004    5454   5565
sweden     2005    5676   5775

我该怎么做呢?

4

2 回答 2

0

我认为直接的方法是将 GDP 值放入border DataFrame. 然后,所需要的只是sum对象groupby,然后执行merge

In [178]:

borderdf[2004]=[datadf2.ix[(item, 2004)].values[0] for item in borderdf.neighbor]
borderdf[2005]=[datadf2.ix[(item, 2005)].values[0] for item in borderdf.neighbor]
gpdf=borderdf.groupby(by=['country']).sum()
df=pd.DataFrame(gpdf.unstack(), columns=['neighborsmeangdp'])
df=df.reset_index()
df=df.rename(columns = {'level_0':'year'})
print pd.ordered_merge(datadf, df)
   country   gdp  year  neighborsmeangdp
0  denmark  2132  2004              7586
1  germany  2132  2004               NaN
2   norway  3433  2004               NaN
3   sweden  5454  2004              5565
4  denmark  2342  2005              8018
5  germany  2342  2005               NaN
6   norway  3433  2005               NaN
7   sweden  5676  2005              5775

[8 rows x 4 columns]

当然,我必须为德国补一些数据,

germany    2132   2004
germany    2342   2005

我相信实际上她做得更好。

于 2014-04-22T17:19:18.657 回答
0

merge您可以使用 pandas函数直接合并两者。这里的诀窍是您实际上希望将您的国家datadf与您的. 然后使用and来获得平均邻居 gdp。最后,与数据合并,得到该国自己的 GDP。例如:borderdfgroupbymean

import pandas as pd
from StringIO import StringIO

border_csv = '''
country, neighbor
sweden, norway
sweden, denmark
denmark, germany
denmark, sweden
'''

data_csv = '''
country, gdp, year
sweden, 5454, 2004
sweden, 5676, 2005
norway, 3433, 2004
norway, 3433, 2005
denmark, 2132, 2004
denmark, 2342, 2005
'''

borders = pd.read_csv(StringIO(border_csv), sep=',\s*', header=1)
data = pd.read_csv(StringIO(data_csv), sep=',\s*', header=1)

merged = pd.merge(borders,data,left_on='neighbor',right_on='country')
merged = merged.drop('country_y', axis=1)
merged.columns = ['country','neighbor','gdp','year']


grouped = merged.groupby(['country','year'])
neighbor_means = grouped.mean()
neighbor_means.columns = ['neighbor_gdp']
neighbor_means.reset_index(inplace=True)

results_df = pd.merge(neighbor_means,data, on=['country','year'])
于 2014-04-22T18:02:54.857 回答