Skip to main content
 首页 » 编程设计

python之从 Pandas 数据框中过滤数据

2024年12月31日10kevingrace

背景:我正在尝试使用 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()