gpt4 book ai didi

python - pivot_table 没有要聚合的数字类型

转载 作者:太空狗 更新时间:2023-10-29 21:13:08 27 4
gpt4 key购买 nike

我想根据以下数据框制作一个数据透视表,其中包含列 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

最佳答案

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

关于python - pivot_table 没有要聚合的数字类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39229005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com