【问题标题】:Adding dataframe with different index to time series将具有不同索引的数据框添加到时间序列
【发布时间】:2020-09-14 11:29:23
【问题描述】:

我有一个类似的时间序列

             var
date 
2020-03-10   77
2020-03-11   88
2020-03-12   99 

我还有另一个与上述时间序列大小完全相同的数据框

        mean 
0        12
1        13
2        14 

我想将这个平均列添加到上述时间序列中

             var    mean
date 
2020-03-10   77      12
2020-03-11   88      13
2020-03-12   99      14

我尝试搜索但没有任何结果。

【问题讨论】:

标签: python pandas python-2.7 dataframe time-series


【解决方案1】:

您可以分配 numpy 数组以防止数据对齐(创建列填充缺失值,因为不同的索引值):

df1 = df1.assign(mean = df2['mean'].to_numpy())

或者:

df1['mean'] = df2['mean'].to_numpy()

另一个想法是更改df2 中的索引与df1 相同,因此可以使用DataFrame.join

df2 = df2.set_index(df1.index)
df1 = df1.join(df2)

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 2014-04-19
    • 2018-10-07
    • 1970-01-01
    • 2016-08-11
    • 2021-03-12
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多