2016-08-30 17 views
4

我想从以下数据框中创建一个数据透视表,其列sales,rep。数据透视表显示sales,但不显示rep。当我只用rep尝试时,我得到了错误DataError: No numeric types to aggregate。如何解决这一问题,使得我看到这两个数字字段sales和场(串)reppivot_table没有要汇总的数字类型

data = {'year': ['2016', '2016', '2015', '2014', '2013'], 
     'country':['uk', 'usa', 'fr','fr','uk'], 
     'sales': [10, 21, 20, 10,12], 
     'rep': ['john', 'john', 'claire', 'kyle','kyle'] 
     } 

print pd.DataFrame(data).pivot_table(index='country', columns='year', values=['rep','sales']) 

     sales    
year  2013 2014 2015 2016 
country      
fr  NaN 10 20 NaN 
uk   12 NaN NaN 10 
usa  NaN NaN NaN 21 


print pd.DataFrame(data).pivot_table(index='country', columns='year', values=['rep']) 
DataError: No numeric types to aggregate 
+0

这取决于你正在努力去做。默认的agg函数是'mean',你不能考虑销售代表的意思。请更改agg函数或传递另一列的值。如果你只是想使用枢轴,使用枢轴而不是pivot_table。 – ayhan

回答

13

你可以使用​​和unstack

df = pd.DataFrame(data) 
df.set_index(['year','country']).unstack('year') 

产量

  rep      sales     
year  2013 2014 2015 2016 2013 2014 2015 2016 
country             
fr  None kyle claire None NaN 10.0 20.0 NaN 
uk  kyle None None john 12.0 NaN NaN 10.0 
usa  None None None john NaN NaN NaN 21.0 

或者,使用pivot_tableaggfunc='first'

df.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first') 

产生

  rep      sales     
year  2013 2014 2015 2016 2013 2014 2015 2016 
country             
fr  None kyle claire None None 10 20 None 
uk  kyle None None john 12 None None 10 
usa  None None None john None None None 21 

aggfunc='first'随着每个(country, year, rep)(country, year, sales) 组是通过取找到的第一个值aggregrated。在你的情况下,似乎没有重复,所以第一个值与唯一值相同。

+1

set_index,它的巫毒,发誓它伏都教! – Merlin

1

看来,问题来自于不同类型的列代表和销售,如果转换的销售str类型,并指定aggfunc为sum,它工作正常:

df.sales = df.sales.astype(str) 

pd.pivot_table(df, index=['country'], columns=['year'], values=['rep', 'sales'], aggfunc='sum') 

#  rep       sales 
# year 2013 2014 2015 2016 2013 2014 2015 2016 
# country        
# fr None kyle claire None None  10  20 None 
# uk kyle None None john  12 None None 10 
#usa None None None john None None None 21