0

MY DataFrame contains several data for each date. in my date column date has entered only for the first data of the day, for rest of the data of the day there is only sparse value. How can I fill all the all the unfilled date values with corresponding date?

Following is the snippet of my data frame

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
code
  • 13
  • 1
  • 5
  • 1
    Please provide data as plain text, not images. Also, do you want a python/pandas solution, an R solution or both? – neilfws Oct 30 '17 at 22:09
  • 3
    Possible duplicate of [How to replace NaNs by preceding values in pandas DataFrame?](https://stackoverflow.com/questions/27905295/how-to-replace-nans-by-preceding-values-in-pandas-dataframe) – 0TTT0 Oct 30 '17 at 22:11
  • 1
    Please do not post images of code or data. – wwii Oct 30 '17 at 22:16
  • Spamming tags for is not cool. "pandas" has nothing to do with R (and I'm being kind by not referring maliciously to python-related ilk), – hrbrmstr Oct 30 '17 at 23:31

2 Answers2

3

In Python

df['Date']=df['Date'].replace({'':np.nan}).ffill()

In R

library(zoo)
df$Date[df$Date=='']=NA
df$Date=na.locf(df$Date)
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Thank you Wen! It is working and I learned something which I didn't know. May you please elaborate the code to me! – code Oct 31 '17 at 20:17
  • @DharitParmar Basically R and Python are same here, replace the blank with np.nan, `ffill` and `na.locf` is to fill the `na` by using the previous not null value – BENY Oct 31 '17 at 20:33
  • @ Wen Understood, Thank you! – code Oct 31 '17 at 20:52
3

You can use fillna function.

# Say df is your dataframe
# To fill values forward use:
df.fillna(method='ffill') 

# To fill values backward use:
df.fillna(method='bfill')
Pal
  • 920
  • 6
  • 6