【问题标题】:Pandas/Python: Find missing values in time series, insert a new time stamp and a nan value for missing values [duplicate]Pandas/Python:查找时间序列中的缺失值,插入新的时间戳和缺失值的 nan 值 [重复]
【发布时间】:2020-10-23 01:13:14
【问题描述】:

我创建了以下 DataFrame:

import pandas as pd

d = {'T': [1, 2, 4, 15], 'H': [3, 4, 6, 8]}
df = pd.DataFrame(data=d, index=['10.09.2018  13:15:00','10.09.2018  13:30:00', '10.09.2018  14:00:00', '10.09.2018  22:00:00'])
df.index = pd.to_datetime(df.index)

并得到以下结果。

Out[30]: 
                      T  H
2018-10-09 13:15:00   1  3
2018-10-09 13:30:00   2  4
2018-10-09 14:00:00   4  6
2018-10-09 22:00:00  15  8

如您所见,在 13:45:00 缺少一个值,在 14:00 和 22:00 之间缺少很多值。

有没有办法自动查找缺失值,插入一行缺失时间戳和缺失时间的 nan 值?

我想实现这个:

Out[30]: 
                      T  H
2018-10-09 13:15:00   1  3
2018-10-09 13:30:00   2  4
2018-10-09 13:45:00  nan nan
2018-10-09 14:00:00   4  6
2018-10-09 14:15:00  nan nan
...
2018-10-09 21:45:00  nan nan
2018-10-09 22:00:00  15  8

【问题讨论】:

  • df.resample("900S").sum()?
  • 使用df.asfreq('15T')

标签: python pandas datetime time series


【解决方案1】:

您可以使用正确的时间步长创建第二个数据框作为索引,并将其与原始数据连接。以下代码适用于我的情况

# your code
import pandas as pd

d = {'T': [1, 2, 4, 15], 'H': [3, 4, 6, 8]}
df = pd.DataFrame(data=d, index=['10.09.2018  13:15:00','10.09.2018  13:30:00', '10.09.2018  14:00:00', '10.09.2018  22:00:00'])
df.index = pd.to_datetime(df.index)

# generate second dataframe with needed index
timerange = pd.date_range('10.09.2018  13:15:00', periods=40, freq='15min')
df2 = pd.DataFrame(index=timerange)

# join the original dataframe with the new one
newdf = df.join(df2, how='outer')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2016-01-16
    • 2018-05-14
    • 2018-08-24
    • 2016-07-28
    • 2020-02-05
    • 2021-03-07
    相关资源
    最近更新 更多