【问题标题】:groupby with apply: ffill(), bfillgroupby 与 apply: ffill(), bfill
【发布时间】:2022-07-27 21:38:19
【问题描述】:

我有一个大数据框,我想在其中使用 bfill().ffill()。从其他问题和答案中我知道 bfill()/ffill() 并不能真正在 groupby 上工作,应该使用 apply() 如下:

temp = pd.DataFrame({'group':[1,2,1,2,1,2], 'order':[2,2,3,1,1,3], 'a':[2,2,3,np.nan,np.nan,np.nan], 'b':[np.nan,7,3,8,np.nan,4]})
for i in temp.columns:    
   temp.loc[temp['group']==1, i ] = temp.sort_values(by =['order'], ascending = [True]).groupby('group').apply(lambda x: x.bfill().ffill())

这行得通。

但是,当我在我的数据集上运行它时,它总是因为内存而崩溃。有关如何使用替代品或更好地管理 RAM 的任何建议?

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    这里不需要循环

    temp = temp.sort_values(by =['order'], ascending = [True]).groupby('group').apply(lambda x: x.bfill().ffill())
    

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 2023-01-31
      • 1970-01-01
      • 2022-10-24
      • 2018-04-23
      • 2020-11-18
      • 2023-03-30
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多