首页 > 解决方案 > 从 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()

所以我的问题是,我怎样才能找到所有独特患者的平均年龄?

标签: pythonpandasdataframe

解决方案


您可以简单地使用可用的groupby函数pandas,但对相关列有限制:

ptid_ages_noshow[['PatientId','Ages']].groupby('PatientId').mean()

推荐阅读