pandas Python:将每日列表集成到带有小时索引的df中

cuxqih21  于 2022-11-05  发布在  Python
关注(0)|答案(2)|浏览(233)

我有每日的weather数据:

  1. rain (mm)
  2. date
  3. 01/01/2022 0.0
  4. 02/01/2022 0.5
  5. 03/01/2022 2.0
  6. ...

我有另一个按小时细分的表(df

  1. value
  2. datetime
  3. 01/01/2022 01:00 x
  4. 01/01/2022 02:00 x
  5. 01/01/2022 03:00 x
  6. ...

我想这样加入他们:

  1. value rain
  2. datetime
  3. 01/01/2022 01:00 x 0.0
  4. 01/01/2022 02:00 x 0.0
  5. 01/01/2022 03:00 x 0.0
  6. ...
  7. 02/01/2022 01:00 x 0.5
  8. 02/01/2022 02:00 x 0.5
  9. 02/01/2022 03:00 x 0.5
  10. ...
  11. 03/01/2022 01:00 x 2.0
  12. 03/01/2022 02:00 x 2.0
  13. 03/01/2022 03:00 x 2.0
  14. ...

(nb:所有日期均为d%/m%/Y%格式,并且所有日期均为各自df的索引)
我肯定有一个直接的解决方案,但我找不到它...提前感谢任何帮助!

eaf3rand

eaf3rand1#

您可能需要对weather重新采样,然后连接df

  1. weather = weather.resample("H").ffill()
  2. df_out = weather.join(df)

这将保留weather的重采样索引,您可能希望保留df索引或交集,或者所有索引。请查看doc和kwarg how
输出(默认值how="left"):

  1. rain (mm) value
  2. date
  3. 2022-01-01 00:00:00 0.0 NaN
  4. 2022-01-01 01:00:00 0.0 x
  5. 2022-01-01 02:00:00 0.0 x
  6. 2022-01-01 03:00:00 0.0 x
  7. 2022-01-01 04:00:00 0.0 NaN
  8. ... ... ...
  9. 2022-02-28 20:00:00 0.5 NaN
  10. 2022-02-28 21:00:00 0.5 NaN
  11. 2022-02-28 22:00:00 0.5 NaN
  12. 2022-02-28 23:00:00 0.5 NaN
  13. 2022-03-01 00:00:00 2.0 NaN
展开查看全部
nnsrf1az

nnsrf1az2#

假设第一个 Dataframe 命名为“天气”,第二个命名为“df”。
让我们试试下面的代码:

  1. df['rain']=[weather['rain (mm)'][i] for i in df.index]

相关问题