2013-05-02 10 views

risposta

16

è possibile eseguire un'operazione groupby/forward-fill su ciascun gruppo:

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) 

cede

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 
+0

L'opzione 'ffill' è quello che mi serve. Grazie! – ChrisB

+1

Puoi anche fare 'df ['x'] = df.groupby ('id'). Fillna (method = 'ffill')' per ottenere lo stesso risultato per una sintassi leggermente più semplice. – Zhang18

+0

@ Zhang18: Grazie per il miglioramento. 'df.groupby (['id']). ffill()' funzionerebbe anche. – unutbu

Problemi correlati