sumeyyeemir
sumeyyeemir

Reputation: 235

How can I extend a data frame with date range in two columns using python?

How do I expand the time range of information in a dataframe as a new data frame.

 "start"     "end"      "note"   "item"
2016-12-30  2017-01-03    Z        1
2017-09-10  2017-09-14    W        2
 "start"      "note"    "item"
2016-12-30     Z         1
2016-12-31     Z         1
2017-01-01     Z         1
2017-01-02     Z         1
2017-01-03     Z         1
2017-09-10     W         2
2017-09-11     W         2
2017-09-12     W         2
2017-09-13     W         2
2017-09-14     W         2

How can I do it using python.

Upvotes: 1

Views: 352

Answers (1)

jezrael
jezrael

Reputation: 862441

Use:

#convert columns to datetimes if necessary
df[['start','end']] = df[['start','end']].apply(pd.to_datetime)
#repeat datetimes to Series
s = pd.concat([pd.Series(r.Index,pd.date_range(r.start, r.end)) 
                         for r in df.itertuples()])

#repoeat values, remove end column and reaasign start by index values
df = df.loc[s].drop(['end'], axis=1).assign(start=s.index).reset_index(drop=True)
print (df)
       start note  item
0 2016-12-30    Z     1
1 2016-12-31    Z     1
2 2017-01-01    Z     1
3 2017-01-02    Z     1
4 2017-01-03    Z     1
5 2017-09-10    W     2
6 2017-09-11    W     2
7 2017-09-12    W     2
8 2017-09-13    W     2
9 2017-09-14    W     2

Upvotes: 2

Related Questions