我有一个当前迭代,根据创建的新series
将新行填充到dataframe
:
for i in range (x):
nextMonth = df.index[-1] + DateOffset(months=1)
newRow = pd.Series({'col_1':None,'col_2':1}, name=nextMonth)
df = df.append(newRow)
这很好用。在正确的df
列(col_1
和col_2
(上创建新行,并且我在df
(date
上的2022-02-01
(上有一个正确的名为nextMonth
的索引。
col_1 col_2
date
1994-07-01 0.0684 7.177511
1994-08-01 0.0186 6.718000
1994-09-01 0.0153 6.595327
1994-10-01 0.0262 6.495939
1994-11-01 0.0281 6.330091
... ... ...
2021-10-01 0.0125 1.035140
2021-11-01 0.0095 1.022360
2021-12-01 0.0073 1.012739
2022-01-01 0.0054 1.005400
2022-02-01 NaN 1.000000 -----> series added
请注意,我使用series
命名索引来匹配df
列,并且我还使用series
名称在最终的df
上将其用作命名索引(nextMonth
(。
由于df.append()
将被弃用,我正在努力使用df.concat()
执行相同的指令。
通过稍微修改循环,可以使构建字典成为dict理解;用它构造一个DataFrame;则使用CCD_ 17将其连接到CCD_。例如,如果x=3
:
x = 3
df = (pd.concat((df, pd.DataFrame.from_dict(
{df.index[-1] + DateOffset(months=i+1): {'col_1':np.nan, 'col_2':1}
for i in range(x)}, orient='index')))
.rename_axis(index=df.index.name))
输出:
col_1 col_2
date
1994-07-01 0.0684 7.177511
1994-08-01 0.0186 6.718000
1994-09-01 0.0153 6.595327
1994-10-01 0.0262 6.495939
1994-11-01 0.0281 6.330091
2021-10-01 0.0125 1.035140
2021-11-01 0.0095 1.022360
2021-12-01 0.0073 1.012739
2022-01-01 0.0054 1.005400
2022-02-01 NaN 1.000000
2022-03-01 NaN 1.000000
2022-04-01 NaN 1.000000