A1122 A1122 - 2 months ago 14
Python Question

How to search datetime index and place None-values to another variables whenever it is weekend Python

Say that I have a pandas

df
which contains financial time-series data with datetime index. An example:

x = ['10-06-2016', '10-07-2016', '10-10-2016', '10-11-2016', '10-12-2016']
y = [0,1,2,3,4]


Note that I don't have time-series values on weekends, which is why '10-08-2016' and '10-09-2016' are not printed on dataframe index.

I wish to create a new
y
vector which places
None
in spots where weekends are.

So ideal output:

x = ['10-06-2016', '10-07-2016', '10-08-2016', '10-09-2016', '10-10-2016', '10-11-2016', '10-12-2016']
y = [0,1,None,None,2,3,4]


What's the best way to accomplish this? Since
x
is not printing the weekends, how do I search
x
is weekend and then insert
None
values to
y
?

Answer

You can reindex the data frame which has a datetimeIndex with a wider range of date as follows, missing values will be filled with NaN:

import pandas as pd
df = pd.DataFrame({'Value': y}, index=pd.to_datetime(x))

#       Value
#2016-10-06 0
#2016-10-07 1
#2016-10-10 2
#2016-10-11 3
#2016-10-12 4

df.reindex(pd.date_range(start = df.index.min(), end = df.index.max()))

#         Value
#2016-10-06 0.0
#2016-10-07 1.0
#2016-10-08 NaN
#2016-10-09 NaN
#2016-10-10 2.0
#2016-10-11 3.0
#2016-10-12 4.0