根据 python pandas 中的日期删除非重复记录

Remove non-duplicate records based on date in python pandas

我的数据结构如下: sample patient data

基本上,这是一份患者名单,他们在某个日期接受了一对血液检测(A,B),但他们本可以在另一个日期分别进行其中的一项血液检测(其中许多were),这些记录都混在一起,所以我的数据是这样的:

test_date patient# test_type result
20191001        1      A        77
20191001        2      A        34
20191001        2      B        66
...            ...    ...      ...
20191011        15     A        111
20191011        15     B        222
20191011        1      A        32
20191011        1      B        99

到目前为止,我一直在 python (pandas, numpy) 中清理数据,现在我正尝试按日期删除不重复的患者# 记录(删除在给定日期仅接受一次测试的患者行),因为我只想比较在同一日期接受两项测试的患者的测试结果(A,B)。

这里最大的警告是,例如,患者 #1 可能在 2019 年 10 月 1 日只接受了测试 A,但在 2019 年 10 月 2 日确实接受了测试 A 和 B and/or其他一些日期(一名患者可能已经在多个日期接受了这两项测试)。因此,在该示例中,我想丢弃患者 #1 的 2019-10-01 测试记录,但保留 2019-10-02 的测试记录(以及任何后续对)。

理想情况下,我的最终数据应该是这样的: cleaned data

我曾尝试对患者编号使用 duplicated()drop_duplicates() 来过滤数据,但这在这种情况下不起作用,因为所有患者都至少在一个给定日期接受了这两项测试。

这可以使用 2 个分组依据和一个合并来完成。代码中的注释应该有助于解释正在做什么。

# get count of # tests for each patient-date combination
grp_df = df.groupby(['PATIENT','DATE'], as_index=False)\
            .agg({'TEST':'count'})\
            .rename(columns = {'TEST':'TEST_CT'})\
            .sort_values(['PATIENT','DATE'])

filt_df = grp_df[grp_df['TEST_CT'] == 2]\ # filter days when patients got both tests only
            .groupby(['PATIENT'], as_index=False)\ 
            .agg({'DATE':'max'}) # get latest date for a patent when both tests were done

op_df = pd.merge(df, filt_df, on = ['PATIENT','DATE']) # filter original data to only include selected patient-date combinations
op_df