I have list of start and end dates which I want to convert into 1 large dataframe.
here is a small reproductible example of what I am trying to acheive
import pandas as pd
from pandas.tseries.offsets import *
import datetime as dt
dates = pd.DataFrame([[dt.datetime(2016,01,01),dt.datetime(2016,02,01)], [dt.datetime(2016,01,10), dt.datetime(2016,02,25)], [dt.datetime(2016,02,10), dt.datetime(2016,03,25)]], columns=['start', 'end'])
which gives me start and end dates such has:
In[14]: dates
Out[14]:
start end
0 2016-01-01 2016-02-01
1 2016-01-10 2016-02-25
2 2016-02-10 2016-03-25
I ma trying to create a dataframe with date ranges of weekdays based on those start / end dates and append them together.
this is how I approch the problem but it doesn't feel too much pythonic:
op_series = list()
for row in dates.itertuples():
time_range = pd.date_range(row.start, row.end, freq=BDay())
s = len(time_range)
op_series += (zip(time_range, [row.start]*s, [row.end]*s))
df = pd.DataFrame(op_series, columns=['date', 'start', 'end'])
In[4]: df.head()
Out[4]:
date start end
0 2016-01-01 2016-01-01 2016-02-01
1 2016-01-04 2016-01-01 2016-02-01
2 2016-01-05 2016-01-01 2016-02-01
3 2016-01-06 2016-01-01 2016-02-01
4 2016-01-07 2016-01-01 2016-02-01
is there a more efficient way than creating list of data and them gluing them together?
thanks!
Still a bit clumsy, but probably more efficient than yours, as it's all in numpy. Merge a Dataframe with the appropriate day diffs
df = pd.DataFrame([[dt.datetime(2016,1,1),dt.datetime(2016,2,1)], [dt.datetime(2016,1,10), dt.datetime(2016,2,25)], [dt.datetime(2016,2,10), dt.datetime(2016,3,25)]], columns=['start', 'end'])
df['diff'] = (df['end'] - df['start']).dt.days
arr = np.empty(0, dtype=np.uint32)
diff_arr = np.empty(0, dtype=np.uint32)
for value in df['diff'].unique():
arr = np.append(arr, np.arange(value))
diff_arr = np.append(diff_arr, np.full(value, value, dtype=np.uint32))
tmp_df = pd.DataFrame(dict(diff=diff_arr, i=arr))
tmp_df['i'] = pd.to_timedelta(tmp_df['i'], unit='D')
df = df.merge(tmp_df, on='diff')
df['date'] = df['start'] + df['i']
df.drop(['i', 'diff'], inplace=True, axis=1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.