在pandas数据帧中填写缺失值

时间:2014-04-01 18:16:04

标签: python pandas dataframe

我想在我的pandas数据框中填写缺失值。最理想的是,我希望minute列的范围为每小时0-60。不幸的是,数据生成过程没有记录sub_count = 0的任何行。反正有没有这样做?我的数据包含日期2014-03-312014-04-01

df = 

   sub_count        date  hour  minute
0          1  2014-03-31     0       0
1          1  2014-03-31     0       4
2          1  2014-03-31     0       5
3          1  2014-03-31     0       6
4          2  2014-03-31     0       7
...

1 个答案:

答案 0 :(得分:3)

构建一个DatetimeIndex(您可以在读取数据时执行此操作,具体取决于它的存储方式):

df = df.set_index(pd.to_datetime(df.date + 'T' +
                                 df.hour.astype(str) + ':' +
                                 df.minute.astype(str))

In [23]: df = df['sub_count']

In [24]: df
Out[24]: 
2014-03-31 00:00:00    1
2014-03-31 00:04:00    1
2014-03-31 00:05:00    1
2014-03-31 00:06:00    1
2014-03-31 00:07:00    2
Name: sub_count, dtype: int64

然后重新取样:

In [26]: df.resample('T')
Out[26]: 
2014-03-31 00:00:00     1
2014-03-31 00:01:00   NaN
2014-03-31 00:02:00   NaN
2014-03-31 00:03:00   NaN
2014-03-31 00:04:00     1
2014-03-31 00:05:00     1
2014-03-31 00:06:00     1
2014-03-31 00:07:00     2
Freq: T, Name: sub_count, dtype: float64