The code below produces sample dataframe
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
date_today = datetime.now()
days = pd.date_range(date_today, date_today timedelta(35), freq='D')
np.random.seed(seed=1111)
data = np.random.randint(1, high=100, size=len(days))
df = pd.DataFrame({'test': days, 'col2': data})
df = df.set_index('test')
The value on 1st of December is as follows
df.loc['2021-12-01 22:59:41.332749']
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
CodePudding user response:
Replace values for all days except the first day of the month with NaNs and use .ffill()
df.loc[df.index.day != 1, 'col2'] = np.nan
df['col2'] = df['col2'].ffill()