Fill in missing pandas data with previous non-missing value, grouped by key

谁都会走 提交于 2019-11-28 20:40:00

You could perform a groupby/forward-fill operation on each group:

import numpy as np
import pandas as pd

df = pd.DataFrame({'id': [1,1,2,2,1,2,1,1], 'x':[10,20,100,200,np.nan,np.nan,300,np.nan]})
df['x'] = df.groupby(['id'])['x'].ffill()
print(df)

yields

   id      x
0   1   10.0
1   1   20.0
2   2  100.0
3   2  200.0
4   1   20.0
5   2  200.0
6   1  300.0
7   1  300.0
df
   id   val
0   1   23.0
1   1   NaN
2   1   NaN
3   2   NaN
4   2   34.0
5   2   NaN
6   3   2.0
7   3   NaN
8   3   NaN

df.sort_values(['id','val']).groupby('id').ffill()

    id  val
0   1   23.0
1   1   23.0
2   1   23.0
4   2   34.0
3   2   34.0
5   2   34.0
6   3   2.0
7   3   2.0
8   3   2.0

use sort_values, groupby and ffill so that if you have Nan value for the first value or set of first values they also get filled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!