1

我有一个按日期索引的 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。我怎样才能做到这一点

4

1 回答 1

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
于 2013-01-02T16:19:22.387 回答