Pandas 使用datetime索引在基于日期的dataframe中插入行

Pandas 使用datetime索引在基于日期的dataframe中插入行,pandas,datetime,Pandas,Datetime,在上面的pandas数据框中,我想插入2017年1月24日的一行,其值为0.01,0.4,sat,NaT,我该怎么做?我可以使用iloc和手动插入,但我更喜欢考虑日期时间索引的自动化解决方案我认为您需要: col_A vi_B data_source index_as_date 2017-01-21 0.000000 0.199354 sat 2017-01-21 2017-01-22 0.000000 0.20425

在上面的pandas数据框中,我想插入2017年1月24日的一行,其值为
0.01,0.4,sat,NaT
,我该怎么做?我可以使用iloc和手动插入,但我更喜欢考虑日期时间索引的自动化解决方案

我认为您需要:

               col_A    vi_B    data_source index_as_date
2017-01-21  0.000000  0.199354         sat       2017-01-21
2017-01-22  0.000000  0.204250         NaN           NaT
2017-01-23  0.000000  0.208077         NaN           NaT
2017-01-27  0.000000  0.215081         NaN           NaT
2017-01-28  0.000000  0.215300         NaN           NaT
#if necessary convert to datetime
df.index = pd.to_datetime(df.index)
df['index_as_date'] = pd.to_datetime(df['index_as_date'])

df.loc[pd.to_datetime('2017-01-24')] = [0.01,0.4,'sat', pd.NaT]
df = df.sort_index()
print (df)

            col_A      vi_B data_source index_as_date
2017-01-21   0.00  0.199354         sat    2017-01-21
2017-01-22   0.00  0.204250         NaN           NaT
2017-01-23   0.00  0.208077         NaN           NaT
2017-01-24   0.01  0.400000         sat           NaT
2017-01-27   0.00  0.215081         NaN           NaT
2017-01-28   0.00  0.215300         NaN           NaT