python - 从 Pandas 数据框中过滤数据
问题描述
背景:我正在尝试使用 csv 文件中的数据来提出问题并根据数据得出结论。该数据是巴西一家诊所的患者就诊记录,包括额外的患者数据,以及患者是否没有出现。我选择检查患者年龄与未出现数据之间的相关性。
问题:给定就诊次数、患者 ID、年龄和未显示数据,我如何编译与每个唯一患者 ID 相关的年龄数组(以便我可以评估访问诊所的所有唯一患者的平均年龄)。
我的代码:
# data set of no shows at a clinic in Brazil
noshow_data = pd.read_csv('noshowappointments-kagglev2-may-2016.csv')
noshow_df = pd.DataFrame(noshow_data)
这是代码的开头,给出了 csv 的整个数据帧的头部
# Next I construct a dataframe with only the data I'm interested in:
ptid = noshow_df['PatientId']
ages = noshow_df['Age']
noshow = noshow_df['No-show']
ptid_ages_noshow = pd.DataFrame({'PatientId' : pt_id, 'Ages' : ages,
'No_show' : noshow})
ptid_ages_noshow
在这里,我对数据进行了排序以显示一个独特患者的多次访问
# Now, I know how to determine the total number of unique patients:
# total number of unique patients
num_unique_pts = noshow_df.PatientId.unique()
len(num_unique_pts)
如果我想在所有访问过程中找到所有患者的平均年龄,我会使用:
# mean age of all vists
ages = noshow_data['Age']
ages.mean()
所以我的问题是,我怎样才能找到所有独特患者的平均年龄?
解决方案
您可以简单地使用可用的groupby函数pandas
,但对相关列有限制:
ptid_ages_noshow[['PatientId','Ages']].groupby('PatientId').mean()
推荐阅读
- c++ - 如何在 C++ 中以最快的方式读取文件?将数据发送到“顶点缓冲区对象”
- azure-media-services - Azure 媒体服务 V3 - 如何获取 ParentAssets(在 V2 的 IAsset 中可用)
- javascript - Node JS 将一个可能未定义的 JavaScript 对象传递给 pug 模板
- python - Python中的连接单元测试
- java - 从字符串中获取以空格分隔的 2 个整数
- angular - Angular ng-repeat 不起作用,但我可以单独显示数组元素
- c# - 如何在 C# 中获取 while 循环以在单行上打印
- highcharts - 使用 Highcharts 在极坐标图中旋转 xAxis 类别?
- angular - 在角度 5 中,为了使用 routerLink 路由到另一个组件视图,绝对需要什么?
- point-cloud-library - 用于 PCL 的二维 ICP