Higashi Yutaka
Higashi Yutaka

Reputation: 181

How to fill out missing time data by using pandas

I have a pd data series like below. For some reasons, it doesn't have data through 2018-07-26 13:30:00 ~ 2018-08-03 15:45:00

13     2018-03-13 16:40:00      12   12.07          0       
14     2018-03-13 16:41:00      13   12.07          0       
15     2018-03-13 16:42:00      12   12.07          0       
 …
230000 2018-07-26 13:30:00      45   12.07          0
230001 2018-08-03 15:45:00      30   12.07          0
230002 ....
…

I wanted to fill these blank out with 0 and tried "pandas.Series.asfreq" like this

df1= df.asfreq("T",fill_value=0)
print(df1)

but it gave me a weird response like below.

1970-01-01       0    0    0

Could you teach me how to fill out those blanks?

Upvotes: 2

Views: 54

Answers (1)

Chris Adams
Chris Adams

Reputation: 18647

IIUC, I believe you need to use DataFrame.set_index first, setting the index to your datetime column.

Here is a basic example, but you would substitute 'datetime_col' for the actual name of your own datetime column:

# If necessary, cast datetime column to correct dtype
# df['datetime_col'] = pd.to_datetime(df['datetime_col']) 

df_new = df.set_index('datetime_col').asfreq('T', fill_value=0).reset_index()

Upvotes: 4

Related Questions