簡體   English   中英

將pandas DataFrame DatetimeIndex延長25周

[英]Extend pandas DataFrame DatetimeIndex by 25 week days

我一直在嘗試將我的Pandas DataFrame日期索引延長25周。 我編寫的以下測試示例演示了該問題。 工作日已正確生成,但是沒有將其附加到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)

代碼以錯誤級別0退出,是否有任何想法為何未按預期更新DataFrame?

您正在嘗試以工作日為索引向數據框添加行,因此一種簡單的方法是

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)

對代碼做了一些更改(注釋中的解釋)

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
.......................
....................
....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM