我正在尝试从 csv 文件创建一个表来给我一个变量的比例

问题描述

以下代码是我所拥有的,但它抛出了一个代码,说没有要聚合的数字类型。 代码

import pandas
import numpy as np
link = 'https://raw.githubusercontent.com/dvanderelst-python-class/python-class/spring2021/assignment_data/young_people_survey.csv'
data = pandas.read_csv(link,index_col=0)

data.groupby(['Age','Smoking']).agg(np.mean)
table = pandas.pivot_table(data,index= ['Age'],columns=None,values=['Smoking'],aggfunc={'Smoking':[np.mean]},fill_value=0)

我想得到一个看起来像这样的表: [表应该是什么样子的示例][1] [1]:https://i.stack.imgur.com/4Li38.png

我在 Pandas 中运行时收到的错误消息: Error message

解决方法

在您的 groupby 中,您是在说要对哪些列进行分组(年龄和吸烟),而不是要计算平均值的列。当它尝试计算值为“从不吸烟”的 Smoking 列的平均值时,“前吸烟者”表示这不是数字列。

如果您将 groupby 更改为

data.groupby(['Age','Smoking']).agg({'Height': 'mean','Weight': 'mean'})

您将获得每个年龄和吸烟类别组合的平均身高和体重

,
import pandas
import numpy as np
link = 'https://raw.githubusercontent.com/dvanderelst-python-class/python-class/spring2021/assignment_data/young_people_survey.csv'
data = pandas.read_csv(link,index_col=0)
data['Age'] = data['Age'].astype(float)
data.groupby(['Age','Smoking']).agg(np.mean)
table = pandas.pivot_table(data,index= ['Age'])

这将给出如下表格

enter image description here