我有一堆外贸统计数据堆积在一个表/csv中:
年份、is_export (否则为进口)、国家、海关代码、宏代码(一组海关代码)和价值(以美元计)。
我希望能够使用熊猫对数据进行分组(而不是使用普通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...等
发布于 2015-03-03 09:49:31
还不完全清楚您的预期输出是什么(考虑到您提供的数据)。我想你想要的是每个国家和每年的总价值(如果不是,请随时纠正我):
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.2https://stackoverflow.com/questions/28827522
复制相似问题