使用日期时间索引在pandas数据框中插入行

3
               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

在上述的Pandas数据框中,我想插入一行2017年1月24日的数据,值为0.01, 0.4, sat, NaT,我该如何操作呢?我可以使用iloc手动插入,但我更喜欢自动化解决方案并考虑到datetime索引。
1个回答

2

我认为你需要使用扩展设置sort_index

#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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接