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并手动插入,但我更喜欢自动解决方案,它考虑了日期时间索引
答案 0 :(得分:1)
我认为setting with enlargement需要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