python pandas timeseries:为时间赋值(当前从索引中省略)

时间:2014-12-20 10:34:11

标签: python pandas

我想为索引中当前不存在的时间序列中的时间分配值,将其插入正确的位置。即2014-01-02以下内容:

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

分配后,ts应为:

2014-01-02    1 # or whatever
2014-01-03    1.876969
...
2014-01-08    0.907479
Freq: D, dtype: float64

(或者更常见的是基于时间/日期的正确位置。)这是我尝试过的:

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

我认为必须有办法做一些看似简单的事情,但它肯定没有跳出来......

1 个答案:

答案 0 :(得分:1)

有时您可能不希望对索引进行排序。所以熊猫不会自动这样做。如果您确实要对索引进行排序,请致电sort_index

ts['2014-01-02'] = 1 
ts = ts.sort_index()

产量

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