如何在 Python 中访问聚合函数的值

E B*_*E B 5 python aggregate pandas

我创建了一个数据帧并分组和聚合时间戳,为每个分组提供最小值和最大值,结果数据帧看起来像这个 DF 定义为病人 ID,时间戳我按病人 ID 对 DF 进行分组,然后我想获取最小值和最大值每个组的最大时间戳,我这样做了

bypatient_date = pd.DataFrame(byencounter.agg({'timestamp' : [np.min,np.max]})).reset_index())

  patient_id  timestamp            
              amin        amax
0         19  3396-08-21  3396-08-25
1         99  2723-09-27  2727-03-17
2       3014  2580-12-02  2581-05-01
3      24581  3399-07-19  3401-04-13
Run Code Online (Sandbox Code Playgroud)

我正在尝试找出每个患者 ID 的最小值和最大值之间的差异,但在尝试访问时间戳 amin 和时间戳 amax 中的值时遇到问题有没有办法在不循环但使用内置 pandas 或 numpy 的情况下执行此操作

Par*_*ait 7

只需删除列索引的最外层,如本SO 帖子所示。然后aminamax可以作为自己的列进行访问,您可以在其中获取差异:

bypatient_date = pd.DataFrame(byencounter.groupby('patient_id').\
                              agg({'timestamp' : [np.min, np.max]})).reset_index(drop=True)

bypatient_date.columns = bypatient_date.columns.droplevel(0)
bypatient_date['datediff'] = bypatient_date['amax'] - bypatient_date['amin']
Run Code Online (Sandbox Code Playgroud)