IIUC,你可以使用.loc:
idx = len(dfr) # get the index of the next row after the last one
dfr.loc[idx, ('A', 'Datetime')] = pd.to_datetime('2021-09-24')
dfr.loc[idx, ('B', 'Str')] = 'Hello'
dfr.loc[idx, ('C', 'Ret')] = 4.3
输出:
>>> dfr
A B C
Datetime Str Ret Datetime Str Ret Datetime Str Ret
0 2021-09-24 00:00:00 NaN NaN NaN Hello NaN NaN NaN 4.3
更新
我的意思是,例如,当我在不同列中有不同数量的值时(例如,A-Str 列中有 6 个值,但 B-Datetime 列中只有 4 个)但我真的不知道。在这种情况下,我需要在最后一个值之后添加该列中的下一个值,因此我需要知道该特定列的最后一个非 Nan 值的索引,以便我可以在您的答案中使用它,因为如果我使用 len( dfr) 在尝试向只有 4 个值的列添加值时,它最终会出现在第 7 行而不是第 5 行,这是因为其中一列的值可能比其他列多。
您可以使用last_valid_index 轻松完成。创建一个方便的函数append_to_col 在数据框中就地附加值:
def append_to_col(col, val):
idx = dfr[col].last_valid_index()
dfr.loc[idx+1 if idx is not None else 0, col] = val
# Fill your dataframe
append_to_col(('A', 'Datetime'), '2021-09-24')
append_to_col(('A', 'Datetime'), '2021-09-25')
append_to_col(('B', 'Str'), 'Hello')
append_to_col(('C', 'Ret'), 4.3)
append_to_col(('C', 'Ret'), 8.2)
append_to_col(('A', 'Datetime'), '2021-09-26')
输出:
>>> dfr
A B C
Datetime Str Ret Datetime Str Ret Datetime Str Ret
0 2021-09-24 NaN NaN NaN Hello NaN NaN NaN 4.3
1 2021-09-25 NaN NaN NaN NaN NaN NaN NaN 8.2
2 2021-09-26 NaN NaN NaN NaN NaN NaN NaN NaN