如何使用没有孔的时间序列为带有“孔”的DataFrame建立索引

时间:2013-01-02 16:04:22

标签: python pandas time-series

我有一个像这样的日期索引的DataFrame:

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1853141 entries, 2012-03-01 00:00:00 to 2012-06-16 23:59:55
Data columns:
Open Bid ESM2    1853141  non-null values
Open Ask ESM2    1853141  non-null values
dtypes: float64(2)

索引的周期为5秒,有一些“漏洞”,所以我创建了一个具有相同日期范围和周期的TimeSeries,没有漏洞:

<class 'pandas.tseries.index.DatetimeIndex'>
[2012-03-01 00:00:00, ..., 2012-06-16 23:59:55]
Length: 1866240, Freq: 5S, Timezone: None

现在我想使用这个时间序列作为上面的DataFrame的索引,并将列为NaN的孔。我怎么能这样做

1 个答案:

答案 0 :(得分:4)

您可以使用reindex()方法并传递您创建的填充索引 默认fill_valueNaN

In [1]: ix1 = [0, 1, 2, 3, 4, 9]

In [2]: ix1
Out[2]: [0, 1, 2, 3, 4, 9]

In [3]: ix2 = range(10)

In [4]: ix2
Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [5]: s = Series(ix1, index=ix1)

In [6]: s
Out[6]:
0    0
1    1
2    2
3    3
4    4
9    9

In [7]: s.reindex(ix2)
Out[7]:
0     0
1     1
2     2
3     3
4     4
5   NaN
6   NaN
7   NaN
8   NaN
9     9

In [8]: Series.reindex()?

Docstring:
Conform Series to new index with optional filling logic, placing
NA/NaN in locations having no value in the previous index. A new object
is produced unless the new index is equivalent to the current one and
copy=False