Fill rows with consecutive values and above rows using pandas
Here is one way using set_index()
and reindex
and ffill
:
df.set_index('col1').reindex(range(df.col1.min(),df.col1.max()+1)).ffill().reset_index()
#df.set_index('col1').reindex(range(df.col1.min(),df.col1.max()+1),method='ffill')\
#.reset_index()
col1 col2
0 1 A
1 2 A
2 3 B
3 4 B
4 5 B
5 6 A
6 7 A
7 8 A
8 9 A
9 10 C
One way is using reindex
with ffill
:
(df.set_index('col1')
.reindex(range(df.col1.iloc[0], df.col1.iloc[-1]+1))
.ffill()
.reset_index())
col1 col2
0 1 A
1 2 A
2 3 B
3 4 B
4 5 B
5 6 A
6 7 A
7 8 A
8 9 A
9 10 C
Or another way using Series.repeat
:
df.col2.repeat(df.col1.diff().shift(-1).fillna().reset_index(drop=True)