【问题标题】:How to align pandas time series如何对齐熊猫时间序列
【发布时间】:2019-01-11 22:12:28
【问题描述】:

假设我们有以下两个时间序列ts_1ts_2

d = {'date': ['2018-01-01',
              '2018-01-02 12:00:00.000',
              '2018-01-02 13:00:00.000',
              '2018-01-03',
              '2018-01-04'],
        'value': [9, 11, 12, 11, 8]}
df = pd.DataFrame(d)
df['date'] = pd.to_datetime(df['date'])
ts_1 = pd.Series(df['value'].values, index=df['date']).resample('D').count()
greater10 = df[df['value']>10]
ts_2 = pd.Series(greater10['value'].values, index=greater10['date']).resample('D').count()

显然,两个时间序列都没有相同的起点和终点(因此,长度相同),这正是我所需要的。

如何将起点和终点对齐到最大值?缺失值填0

【问题讨论】:

  • 预期输出是什么?

标签: pandas time-series


【解决方案1】:

如果需要查看时间序列的第一个和最后一个值,我相信您需要 concat 和 iloc:

df = pd.concat([ts_1.iloc[[0, -1]], 
                ts_2.iloc[[0, -1]]], axis=1, keys=('ts1','ts2')).fillna(0)
print (df)
            ts1  ts2
date                
2018-01-01  1.0  0.0
2018-01-02  0.0  2.0
2018-01-03  0.0  1.0
2018-01-04  1.0  0.0

如果只需要对齐时间序列:

df = pd.concat([ts_1, ts_2], axis=1, keys=('ts1','ts2')).fillna(0)
print (df)
            ts1  ts2
date                
2018-01-01    1  0.0
2018-01-02    2  2.0
2018-01-03    1  1.0
2018-01-04    1  0.0

另一种解决方案是使用Series.align:

s11, s12 = ts_1.align(ts_2, fill_value=0)
print (s11)
date
2018-01-01    1
2018-01-02    2
2018-01-03    1
2018-01-04    1
Freq: D, dtype: int64

print (s12)
date
2018-01-01    0.0
2018-01-02    2.0
2018-01-03    1.0
2018-01-04    0.0
Freq: D, dtype: float64

s21, s22 = ts_2.align(ts_1, fill_value=0)
print (s21)
date
2018-01-01    0.0
2018-01-02    2.0
2018-01-03    1.0
2018-01-04    0.0
Freq: D, dtype: float6

print (s22)
date
2018-01-01    1
2018-01-02    2
2018-01-03    1
2018-01-04    1
Freq: D, dtype: int64

【讨论】:

  • align 选项正是我想要的。非常感谢!
【解决方案2】:

documentation你应该可以做到

result = pd.concat([ts_1, ts_2], axis=1, join_axes=[ts_1.index])

假设您希望将索引保留在 ts_1 中

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2014-10-08
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多