【问题标题】:Pandas: resample a dataframe to match a DatetimeIndex of a different dataframePandas:重新采样数据帧以匹配不同数据帧的 DatetimeIndex
【发布时间】:2020-11-29 04:53:36
【问题描述】:

我在单独的pandas.dataframe 中有两个时间序列,第一个 - series1 与第二个 - series2 相比条目较少且开始数据时间不同:

index1 = pd.date_range(start='2020-06-16 23:16:00', end='2020-06-16 23:40:30', freq='1T')
series1 = pd.Series(range(len(index1)), index=index1)
index2 = pd.date_range('2020-06-16 23:15:00', end='2020-06-16 23:50:30', freq='30S')
series2 = pd.Series(range(len(index2)), index=index2)

如何重新采样 series2 以匹配 series1DatetimeIndex

【问题讨论】:

  • 重采样时要做什么操作?做一个mean,得到minmax,...?

标签: python pandas time-series resampling pandas-resample


【解决方案1】:

简单的重采样不会产生想要的结果吗?

series2.resample('T').first()

如果您的目标是将重新采样的时间戳合并回第一个数据集,您可以按如下方式进行:

dt_map = {}
for group_label, group_series in series2.resample('T'):
    dt_map.update({x:group_label for x in group_series.index})

# Overwrite the index
series2.index = series2.index.map(dt_map)

注意:如果要执行聚合函数,请坚持使用第一个选项。

【讨论】:

    【解决方案2】:

    使用reindex:

    series2.reindex(series1.index)
    

    输出:

    2020-06-16 23:16:00     2
    2020-06-16 23:17:00     4
    2020-06-16 23:18:00     6
    2020-06-16 23:19:00     8
    2020-06-16 23:20:00    10
    2020-06-16 23:21:00    12
    2020-06-16 23:22:00    14
    2020-06-16 23:23:00    16
    2020-06-16 23:24:00    18
    2020-06-16 23:25:00    20
    2020-06-16 23:26:00    22
    2020-06-16 23:27:00    24
    2020-06-16 23:28:00    26
    2020-06-16 23:29:00    28
    2020-06-16 23:30:00    30
    2020-06-16 23:31:00    32
    2020-06-16 23:32:00    34
    2020-06-16 23:33:00    36
    2020-06-16 23:34:00    38
    2020-06-16 23:35:00    40
    2020-06-16 23:36:00    42
    2020-06-16 23:37:00    44
    2020-06-16 23:38:00    46
    2020-06-16 23:39:00    48
    2020-06-16 23:40:00    50
    Freq: T, dtype: int64
    

    【讨论】:

    • reindex 最适合这种情况:) +1
    【解决方案3】:

    IIUC,这就是你需要的:

    series2[series2.index.isin(series1.index)]
    

    【讨论】:

    • 好主意!但在这个解决方案中,我应该首先确保两个时间序列是同步的......仍然是一个很好的解决方案 - 谢谢!
    • 与@scottboston 的结果相同。这没什么特别的问题,但语法并不那么简单。
    猜你喜欢
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多