【问题标题】:How to check for missing values for a TimeSeries Data(Monthly Data)?如何检查时间序列数据(月度数据)的缺失值?
【发布时间】:2022-01-20 22:44:53
【问题描述】:

例子:

DATE ENERGY_INDEX
0 01/1939 3.3842
1 02/1939 3.4100
2 03/1939 3.4875
3 04/1939 3.5133
4 05/1939 3.5133

如何检查时间序列数据中是否遗漏了任何月份的数据?

我查找缺失值的方法:

df['DATE']=pd.to_datetime(df['DATE'],format='%m/%Y')
df.index=df['DATE']
df['DATE'].max()-df['DATE'].min()` - output - Timedelta('29463 days 00:00:00')
df.shape - output - (969,2)

其实df['DATE']=pd.to_datetime(df['DATE'],format='%m/%Y')就是在日期里面加上日期参数。

【问题讨论】:

  • 嘿@JCaesar,请在编辑后的帖子中找到我尝试过的方法

标签: python time-series missing-data


【解决方案1】:

我建议你使用 Pandas 数据框:

!pip install pandas
import pandas as pd
main_na = pd.Dataframe(your_datas) #Where your_datas is your list or np array
main_na = main_df.notna()
for col in main_na.columns:
    diff = len(main_na[col]) - main_na.count()[col]
    if diff > 0:
        print( f"{len(main_na[col]) - main_na.count()[col]} NaN found in column {col}")
main_df.ffill(inplace=True)
main_df.dropna()

我经常使用的这段代码会在你的数据中打印出 NaN 的数量

但是,如果您遇到可能缺少行的情况,您应该使用您的日期列来创建一个新的时间戳列(看看这里:Python pandas convert datetime to timestamp effectively through dt accessor)。然后将此新列设置为数据框的索引,使用:

main_df.set_index("name of your new timestamp colums")

然后这样做:

main_df.sort_index(ascending=True, inplace=True)
time_df = main_df.copy()
time_df["diff"] = time_df.index
time_df["diff"] = time_df["diff"]-time_df["diff"].shift(1)
time_df = time_df["diff"]
print(time_df.value_counts())

例如,它将显示每一行之间的时间戳差异:

900000.0      68383
4500000.0         3
8100000.0         2
9900000.0         2
17100000.0        2
21600000.0        1
13500000.0        1
14400000.0        1
5400000.0         1
6300000.0         1
Name: diff, dtype: int64

左栏为时间差,右栏为病例数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2022-01-06
    • 2020-09-07
    • 2019-06-09
    相关资源
    最近更新 更多