The code below produces sample dataframe
JavaScript
x
12
12
1
import pandas as pd
2
import numpy as np
3
from datetime import datetime, timedelta
4
5
date_today = datetime.now()
6
days = pd.date_range(date_today, date_today + timedelta(35), freq='D')
7
8
np.random.seed(seed=1111)
9
data = np.random.randint(1, high=100, size=len(days))
10
df = pd.DataFrame({'test': days, 'col2': data})
11
df = df.set_index('test')
12
The value on 1st of December is as follows
JavaScript
1
2
1
df.loc['2021-12-01 22:59:41.332749']
2
Which outputs 9
My question is how to use “ffill” method to have this value 9 for all days of December?
I want the month beginning value to be filled till end of that month
Advertisement
Answer
Replace values for all days except the first day of the month with NaNs and use .ffill()
JavaScript
1
3
1
df.loc[df.index.day != 1, 'col2'] = np.nan
2
df['col2'] = df['col2'].ffill()
3