【问题标题】:Substract dataframes with different timestamp in pandas在熊猫中减去具有不同时间戳的数据帧
【发布时间】:2021-06-27 23:46:43
【问题描述】:

假设我有两个具有相同索引的数据帧

(df1)                          (df2)
Timestamp    A                Timestamp     B
01:00        1                01:00         2
02:00        2                02:00         3
03:00        3                03:00         4

如何减去 df1[i] - df2[i-1]?因为它会自动减去具有相同索引的 2 行。

想要的结果:

Timestamp   C
01:00       NaN
02:00       0
03:00       0

非常感谢您的帮助!!

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    DataFrame.shift 会将索引移动指定的周期数,以便您可以将行 i 与其他 DataFrame 中的行 i-1 对齐。 (确保 'Timestamp' 是您的索引。)

    import pandas as pd
    df1 = pd.DataFrame({'A': [1,2,3]}, 
                       index=pd.Index(['01:00', '02:00', '03:00'], name='TimeStamp'))
    df2 = pd.DataFrame({'B': [2,3,4]}, 
                       index=pd.Index(['01:00', '02:00', '03:00'], name='TimeStamp'))
    

    (df1['A'] - df2['B'].shift()).to_frame('C')
    
                 C
    TimeStamp     
    01:00      NaN
    02:00      0.0
    03:00      0.0
    

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2023-01-31
      • 2015-07-14
      • 2021-06-22
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2020-08-27
      • 2019-02-05
      相关资源
      最近更新 更多