【问题标题】:Create a DataFrame in Pandas using an index from an existing TimeSerie and a column form another TimeSerie使用现有 TimeSerie 中的索引和另一个 TimeSerie 中的列在 Pandas 中创建一个 DataFrame
【发布时间】:2020-05-12 06:43:42
【问题描述】:

我想使用现有 TimeSerie 的索引和具有不同时间索引的另一个 TimeSerie 的值来创建 DataFrame 或 TimeSerie。 TimeSeries 看起来像;

 <class 'pandas.core.series.Series'>
DT
2018-01-02    172.3000
2018-01-03    174.5500
2018-01-04    173.4700
2018-01-05    175.3700
2018-01-08    175.6100
2018-01-09    175.0600
2018-01-10    174.3000
2018-01-11    175.4886
2018-01-12    177.3600
2018-01-16    179.3900
2018-01-17    179.2500
2018-01-18    180.1000
...

<class 'pandas.core.series.Series'>
DT
2018-01-02        NaN
2018-01-09    175.610
2018-01-16    177.360
2018-01-23    180.100
...

我想使用第一个 TS 中的索引,并用来自第二个 TS 的适当索引值填充它。喜欢;

<class 'pandas.core.series.Series'>
DT
2018-01-02   NaN
2018-01-03   NaN
2018-01-04   NaN
2018-01-05   NaN
2018-01-08   NaN
2018-01-09   175.610
2018-01-10   NaN
2018-01-11   NaN
2018-01-12   NaN
2018-01-16   177.360
2018-01-17   NaN
2018-01-18   NaN
...

谢谢

【问题讨论】:

    标签: python pandas dataframe time-series


    【解决方案1】:

    IIUC,使用Series.reindex

    new_s = s2.reindex(s1.index)
    
    #2018-01-02       NaN
    #2018-01-03       NaN
    #2018-01-04       NaN
    #2018-01-05       NaN
    #2018-01-08       NaN
    #2018-01-09    175.61
    #2018-01-10       NaN
    #2018-01-11       NaN
    #2018-01-12       NaN
    #2018-01-16    177.36
    #2018-01-17       NaN
    #2018-01-18       NaN
    #Name: s2, dtype: float64
    

    【讨论】:

    • 它对我描述的问题很有效,谢谢!如果 s2 中有某个索引的行,但在 s1 中没有,是否也可以在新创建的 TS 中获取一个值?这是 s1 中的第一个日期,该日期在 s2 中的日期之后。
    【解决方案2】:

    将您的系列数据结构转换为数据框数据结构,然后使用以下行: pd.merge(TS1,TS2,left_index=True,right_index=True,how='left').iloc[:,-1]

    【讨论】:

    • 从时间序列转换为数据帧,你可以使用:series.to_frame()
    猜你喜欢
    • 2017-05-28
    • 2021-08-09
    • 1970-01-01
    • 2016-02-17
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多