python - Python:如何在 groupby 之后适当地加入 df
问题描述
我有一个df:
df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,2,2],
'Movement_Sequence_No':[1,2,3,4,1,2,3,4],
'Movement_Start_Date':['2020-02-09 22:17:00','2020-02-10 17:19:41','2020-02-17 08:04:19',
'2020-02-18 11:22:52','2020-02-12 23:00:00','2020-02-24 10:26:35',
'2020-03-03 17:50:00','2020-03-17 08:24:19'],
'Movement_End_Date':['2020-02-10 17:19:41','2020-02-17 08:04:19','2020-02-18 11:22:52',
'2020-02-25 13:55:37','2020-02-24 10:26:35','2020-03-03 17:50:00',
'2222-12-31 23:00:00','2020-03-18 18:50:00'],
'Category':['A','A','ICU','A','B','B','B','B'],
'RequestDate':['2020-02-10 16:00:00','2020-02-16 13:04:20','2020-02-18 07:11:11','2020-02-21 21:30:30',
'2020-02-13 22:00:00','NA','2020-03-15 09:40:00','2020-03-18 15:10:10'],
'Test1':['180','189','190','188','328','NA','266','256'],
'Test2':['20','21','15','10','33','30','28','15'],
'Test3':['55','NA','65','70','58','64','68','58'],
'Age':['65','65','65','65','45','45','45','45']})
在进行一些处理以填充缺失值后,我得到了 df2:
# Format df appropriately
df = df.replace('NA', np.nan)
df[['Test1','Test2','Test3','Age']] = df[['Test1','Test2','Test3','Age']].astype(float)
# helper column to segregate non-ICU cols by value 0
df["helper"] = df.groupby("CaseNo")["Category"].transform(lambda d: d.eq("ICU").cumsum())
df2 = df.loc[df["helper"].eq(0)].groupby("CaseNo", as_index=False).fillna(
method='ffill').reset_index().drop('index', axis=1) # ffill will fill NA w the latest/prev test value
如何将 df2 适当地合并回 df,以便在 df 中更新更改?预期结果:
解决方案
据我了解,您可以df.where
在设置两个条件后尝试
out = df.replace('NA',np.nan)
cond = out['Category'].ne('ICU') & out['RequestDate'].isna()
out = out.groupby('CaseNo',as_index=False).fillna(method='ffill').where(cond,df)
#if you want Test3 in row 2 to be NaN and not 'NA'
#out = out.groupby('CaseNo',as_index=False).fillna(method='ffill').where(cond,out)
display(out)
推荐阅读
- localization - Pimcore 添加/编辑本地化和国际化的自定义语言 (i18n/l10n)
- joomla - 安装joomla时如何纠正语法错误意外'='?
- javascript - 如何将具有重复值的数组变异/分组为具有非唯一值数组的单个唯一行?
- javascript - 在没有任何相对路径的情况下,此导入如何工作?
- office365 - 如何以编程方式获取 React Office 加载项中的 PowerPoint 对象组列表?
- rust - 当字段不存在时,从不调用反序列化程序
- swift - UITableViewCell textLabel 未覆盖单元格的整个宽度
- user-interface - 如何使用 QThread 作为子类来防止冻结 GUI?(没有工人对象和 .moveToThread() 方法)
- linux - Setfacl 在 dockerfile 中无法正常工作
- javascript - html 上的一个按钮,用于在准确的时间触发自动播放音频