如何创建NaN间隔持续时间的直方图?

时间:2020-02-03 19:07:01

标签: python pandas datetime histogram nan

我有一个大的数据框,该数据框由日期时间索引(连续的1分钟数据),并且有很多NaN。

我想生成一个NaN发生的直方图,该直方图是NaNs间隔的长度的函数(例如,x轴是NaN“孔”的天数,y轴是该特定孔的数量)。

假设我的数据如下:

2015-01-01 05:57:00     2.136221
2015-01-01 05:58:00     4.101965
2015-01-01 05:59:00     NaN
2015-01-01 06:00:00     8.082413
2015-01-01 06:01:00     9.035858
2015-01-01 06:02:00    10.059280
2015-01-01 06:03:00    11.143933
2015-01-01 06:04:00    12.281069
2015-01-01 06:05:00    NaN
2015-01-01 06:06:00    NaN
2015-01-01 06:07:00    NaN
2015-01-01 06:08:00    16.925832
2015-01-01 06:09:00    18.150440
2015-01-01 06:10:00    19.383795
2015-01-01 06:11:00    NaN
2015-01-01 06:12:00    NaN
2015-01-01 06:13:00    NaN
2015-01-01 06:14:00    NaN
2015-01-01 06:15:00    NaN
2015-01-01 06:16:00    26.530258
2015-01-01 06:17:00    27.868579
2015-01-01 06:18:00    29.320614
2015-01-01 06:19:00    NaN
2015-01-01 06:20:00    NaN
2015-01-01 06:21:00    NaN
2015-01-01 06:22:00    35.854773
2015-01-01 06:23:00    37.639202
2015-01-01 06:24:00    39.406136

然后我想要一个直方图,其中1次出现1分钟孔,2次出现3分钟孔,1次出现5分钟孔。

在我的数据中,NaN间隔要大得多,所以也许我想用几小时或几天来衡量它们的长度。

1 个答案:

答案 0 :(得分:0)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'feature1': [1, np.NaN, 2, np.NaN, 3, 2, 3, 4, np.NaN],
               'feature2': [4, np.NaN, 3, 4, np.NaN, 4, 3, np.NaN, np.NaN]})

def foo(start,stop,df,feat):
    counts = df.loc[start:stop,feat].value_counts(dropna=False)
    counts.plot.bar(grid=True)
    plt.show()

foo(3,8,df,'feature2')

这是您要找的吗?