问题描述
我得到了一个索引从 '2020-01-01 01:00:00+00:00'
到 2020-12-19
的 pandas Series 对象。我想添加值为 '2020-01-01 00:00:00+00:00'
的索引 np.nan
。
data_dict[i]
date_time
2020-01-01 01:00:00+00:00 13
2020-01-01 02:00:00+00:00 13
2020-01-01 03:00:00+00:00 13
2020-01-01 04:00:00+00:00 13
2020-01-01 05:00:00+00:00 13
...
2020-12-18 20:00:00+00:00 25
2020-12-18 21:00:00+00:00 25
2020-12-18 22:00:00+00:00 25
2020-12-18 23:00:00+00:00 25
2020-12-19 00:00:00+00:00 20
当我使用时:
nan = pd.Series([np.nan],index=['2020-01-01 00:00:00+00:00'])
data_dict[i].append(nan)
data_dict[i].sort_index()
好像什么都没发生?
data_dict[i]
date_time
2020-01-01 01:00:00+00:00 13
2020-01-01 02:00:00+00:00 13
2020-01-01 03:00:00+00:00 13
2020-01-01 04:00:00+00:00 13
2020-01-01 05:00:00+00:00 13
...
2020-12-18 21:00:00+00:00 25
2020-12-18 22:00:00+00:00 25
2020-12-18 23:00:00+00:00 25
2020-12-19 00:00:00+00:00 20
我如何将它添加到正确的位置(即:在系列对象的开头)
解决方法
如果使用 .append
将新数据添加到 Series
的末尾,对于 DatetimeIndex
的正确顺序排序值:
s = s1.append(s2).sort_index()
如果需要附加到 Series
的开头,交换顺序 - 将第二个 Series
添加到第一个:
s = s2.append(s1)
编辑:这里有必要分配回 Series.append
并在添加的系列中创建 DatetimeIndex
:
nan = pd.Series([np.nan],index=pd.to_datetime(['2020-01-01 00:00:00+00:00']))
data_dict[i] = data_dict[i].append(nan)
data_dict[i] = data_dict[i].sort_index()