【问题标题】:How to index a DataFrame with "holes" with a TimeSeries without holes如何使用没有孔的 TimeSeries 索引带有“孔”的 DataFrame
【发布时间】:2012-12-17 00:06:25
【问题描述】:

我有一个按日期索引的 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。我该怎么做呢

【问题讨论】:

    标签: python pandas time-series


    【解决方案1】:

    您可以使用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-05-06
      • 1970-01-01
      • 2018-01-15
      • 2019-11-07
      • 2015-03-30
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多