简体   繁体   中英

Extend pandas DataFrame DatetimeIndex by 25 week days

I have been trying to extend my Pandas DataFrame Date Index by 25 week days. The following test example that I wrote demonstrates the problem. Weekdays are being correctly generated, however, they are not being appended to the DataFrame.

import pandas as pd
from business_calendar import Calendar

dates = pd.date_range('20190121', periods=5)
df = pd.DataFrame({'high': (58.22, 57.93, 57.51, 57.89, 58.77), 'low': (57.65, 57.15, 56.98, 57.12, 58.00)}, index=dates)

cal = Calendar()
last_idx = df.index[-1].date()
for i in range(1, 26):
    weekdays = pd.DatetimeIndex([cal.addbusdays(last_idx, i)])
    print("idx_count: {:2d} idx: {}".format(i, weekdays))
    df.index.append(weekdays)
print(df.index)

The code exits with errorlevel 0, any ideas why the DataFrame is not being updated as expected?

You're trying to add rows to your Dataframe with weekdays as the index, so an easy way to do that would be

for i in range(1, 26):
   weekdays = pd.DatetimeIndex([cal.addbusdays(last_idx, i)])
   #If you want the values to be na
   newRow = pd.DataFrame(index=weekdays)
   #Or if you want to give values to the new rows
   newRow = pd.DataFrame({'high': (42), 'low': (0)}, index=weekdays)

   df = df.append(newRow)

del newRow
print(df.index)

Did some changes to the code (explanation in comments) :

import pandas as pd
from business_calendar import Calendar

dates = pd.date_range('20190121', periods=5)
df = pd.DataFrame({'high': (58.22, 57.93, 57.51, 57.89, 58.77), 'low': (57.65, 57.15, 56.98, 57.12, 58.00)}, index=dates)

cal = Calendar()
last_idx = df.index[-1].date()
idx_list=[] #added this line
for i in range(1, 26):
    weekdays = pd.DatetimeIndex([cal.addbusdays(last_idx, i)])
    #print(weekdays[0])
    idx_list.append(weekdays[0]) #appending just the value so weekdays[0]
idx_list.extend(df.index) #extend the list with index
df.reindex(idx_list).sort_index() #reindex the df and sort the index

            high    low
2019-01-21  58.22  57.65
2019-01-22  57.93  57.15
2019-01-23  57.51  56.98
2019-01-24  57.89  57.12
2019-01-25  58.77  58.00
2019-01-28    NaN    NaN
2019-01-29    NaN    NaN
2019-01-30    NaN    NaN
.......................
....................
....

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM