我在一个表/ csv中堆积了一堆统计外贸数据:
年份,is_export(否则为进口),国家/地区,海关代码,宏代码(一组海关代码)和价值(以美元为单位)。
我希望能够使用pandas来对数据进行分组(而不是使用普通的sql),并获得如下信息:
macro_group=12
2012 2013 2014
country
export
我是否只需要进行几次groupby
调用(在要建立层次结构的“键”上)?
编辑:所有行都是相同的:
id|Country|Year|Export|Macro|Code|Codename|Value
1|China|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|0.0
2|Germany|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|59.9
3|Italy|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|33.2
我想得到的是:
**Macro e.g. 23**
China total export
2012 2013 2014
432 34 3243
China total import
2012 2013 2014
4534 345 4354
Russia total import...
等等
尚不清楚您的预期输出是什么(鉴于您提供的数据)。我想您希望获得每个国家/地区和年份的总价值(如果没有,请随时纠正我):
import pandas as pd
########### Setup some test data: #############
s = """id|Country|Year|Export|Macro|Code|Codename|Value
1|China|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|0.0
2|Germany|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|59.9
3|Germany|2013|1|69|6996700|Articles,of iron or steel wire,n.e.s.|80.0
4|Germany|2013|1|69|6996700|Articles,of iron or steel wire,n.e.s.|40.0
5|Italy|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|33.2"""
from StringIO import StringIO
df = pd.read_csv(StringIO(s), sep='|')
pd.Series.__unicode__ = pd.Series.to_string # suppress meta-data when printing
########### The real stuff happens here: #############
macro = 69
group_by = df[df.Macro == macro].groupby(['Country', 'Year'])['Value'].sum()
for country in df.Country.unique():
print '---', country, '---'
print group_by[country]
print
结果为以下输出:
--- China ---
2012 0
--- Germany ---
2012 59.9
2013 120.0
--- Italy ---
2012 33.2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句