我一直在尝试将我的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?
答案 0 :(得分:0)
您正在尝试以工作日为索引向数据框添加行,因此一种简单的方法是
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)
答案 1 :(得分:0)
对代码(注释中的说明)进行了一些更改:
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
.......................
....................
....