首页 > 解决方案 > 根据某些列中的相似值合并行

问题描述

请我需要帮助,我最近开始学习python。请问,如何合并具有相同“PatientID”和相同“Resource”的行,并将“StartDate”和“EndDate”作为合并行的平均值?

在此处输入图像描述

在此处输入图像描述

标签: pythonpandasdataframepandas-groupby

解决方案


Givendfpandas.DataFrame包含您的数据的名称。

要获取每个患者的最早资源StartDateEndDate您可以编写:

# Group by the 'PatientID' and 'Resource' columns
grouped_df =  df.groupby(['PatientID', 'Resource'])

# Select Earliest `StartDate` and `EndDate` from aggregate.
grouped_df = grouped_df.min(['StartDate', 'EndDate'])

# Remove levels from the index.
grouped_df.reset_index(inplace=True)

推荐阅读