pivot_table没有到aggreg的数字类型

2024-04-28 11:07:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从下面的数据框中创建一个透视表,其中包含列salesrep。透视表显示sales,但没有rep。当我只尝试使用rep时,得到了错误DataError: No numeric types to aggregate。如何解决这个问题,以便同时看到数值字段sales和字段(字符串)rep

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

Tags: tonodatafrnanyearcountrytypes
2条回答

似乎问题来自列rep和sales的不同类型,如果将sales转换为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

您可以使用set_indexunstack

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) 组通过获取找到的第一个值而聚合。在您的情况下,似乎没有重复项,因此第一个值与唯一的值相同。

相关问题 更多 >