Reputation: 2089
I'd like to assign a value to a time in a time series that currently doesn't exist in the index, inserting it in the correct position. ie 2014-01-02 for the following:
import pandas as pd
from numpy.random import randn as randn
rng = pd.date_range('1/3/2014', periods=6, freq='D')
ts = pd.Series(randn(len(rng)), index=rng)
ts
Out[23]:
2014-01-03 1.876969
2014-01-04 -0.460700
2014-01-05 0.587874
2014-01-06 0.205369
2014-01-07 -1.319009
2014-01-08 0.907479
Freq: D, dtype: float64
After assignment, ts should be:
2014-01-02 1 # or whatever
2014-01-03 1.876969
...
2014-01-08 0.907479
Freq: D, dtype: float64
(Or more generally in the correct position based on the time/date.) This is what I've tried:
ts['2014-01-02'] = 1 # All append date and value to end
ts[pd.to_datetime('2014-01-02')] = 1
ts[pd.datetime(2014, 1, 2)] = 1
temp = pd.Series([1], index=['2014-01-02'])
ts.append(temp) # No effect
ts.replace(temp) # Error
ts.update(temp) # No effect
I think there must be a way to do something so apparently simple, but it certainly hasn't jumped out at me...
Upvotes: 1
Views: 645
Reputation: 881037
Sometimes you may not want the index to be sorted. So Pandas does not do this automatically. If you do want to sort the index, call sort_index
:
ts['2014-01-02'] = 1
ts = ts.sort_index()
yields
In [75]: ts
Out[75]:
2014-01-02 1.000000
2014-01-03 -0.664830
2014-01-04 0.654928
2014-01-05 0.704723
2014-01-06 0.646540
2014-01-07 0.364220
2014-01-08 -1.346799
dtype: float64
Upvotes: 1