2013-11-22 99 views
1

我是python的新手,并且存在以下问题:Python:通过日期时间索引熊猫系列

我每天都会将测量值导入到pd.series对象中。问题是数据是这样的,每个月总是有31次测量,无论是1月份还是2月份。如果相应的月份少于31天,那么超过该月最后一天的那些日期的测量值将设置为零。但是,一个月内丢失的数据也会设置为零。四月和五月的数据看起来像这样。

1990-04-01 25.870 
1990-04-01 26.205 
1990-04-01 12.283 
1990-04-01 19.630 
1990-04-01 19.239 
1990-04-01 23.614 
1990-04-01 40.891 
1990-04-01 41.152 
1990-04-01 35.935 
1990-04-01 25.682 
1990-04-01 21.674 
1990-04-01 15.818 
1990-04-01 11.413 
1990-04-01 16.522 
1990-04-01 33.543 
1990-04-01 28.727 
1990-04-01 18.043 
1990-04-01 10.326 
1990-04-01 19.159 
1990-04-01 21.848 
1990-04-01 35.250 
1990-04-01 39.152 
1990-04-01 31.522 
1990-04-01 23.152 
1990-04-01 13.250 
1990-04-01 20.705 
1990-04-01 27.304 
1990-04-01 24.478 
1990-04-01 33.674 
1990-04-01 32.591 
1990-04-01  0.000 
1990-05-01 40.370 
1990-05-01 41.609 
1990-05-01 47.478 
1990-05-01 40.682 
1990-05-01 42.587 
1990-05-01 38.826 
1990-05-01 35.543 
1990-05-01 30.955 
1990-05-01 23.543 
1990-05-01  7.857 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01 54.133 
1990-05-01 41.114 
1990-05-01 44.739 
1990-05-01 43.848 
1990-05-01 26.739 
1990-05-01 21.318 
1990-05-01 26.750 
1990-05-01 54.864 
1990-05-01 33.000 
1990-05-01 33.304 
1990-05-01 34.304 
1990-05-01 20.886 
1990-05-01 20.250 
1990-05-01 24.804 
1990-05-01 28.091 
Length: 62 

是否有办法删除那些不属于相应月份的条目并为每一天提供新的时间索引?我需要在一个月内保持零。

+0

我走了一下平底船在这里,因为我没有安装熊猫,但如果你尝试s [['1990-04-01','1990-04-02']],会发生什么? (当然,假设你的系列被称为s)。如果它给你一些合理的话,那么问题现在是一个更加容易理解的问题,可以生成所有有效索引的列表。 – Dave

回答

1

首先,我将与南替换0(象征丢失数据):

s.replace(0, np.nan, inplace=True) 

一种方法是创建作用于每个组的功能(月):

def f(s_month): 
    date = s_month.index[0] 
    # create the month long range 
    rng = pd.date_range(date, date + pd.offsets.MonthEnd(1), freq='D') 
    # throw away results longer than month length 
    s_month = s_month.iloc[0:len(rng)] 
    # reindex those remaining 
    s_month.index = rng 
    return s_month 

注:这需要你有一个DatetimeIndex,即s.index = pd.to_datetime(s.index)

In [11]: s_month = s.loc['1990-04-01'] 

In [12]: f(s_month) 
Out[12]: 
1990-04-01 25.870 
1990-04-02 26.205 
1990-04-03 12.283 
1990-04-04 19.630 
... 
1990-04-28 24.478 
1990-04-29 33.674 
1990-04-30 32.591 
Freq: D, Name: Value, dtype: float64 

使用此与GROUPBY适用于:

In [13]: res = s.groupby(s.index).apply(f) 

In [14]: res 
Out[14]: 
1990-04-01 1990-04-01 25.870 
      1990-04-02 26.205 
      1990-04-03 12.283 
      1990-04-04 19.630 
... 

纠正多指标:

In [15]: res.index = res.index.droplevel(0) 

In [16]: res 
Out[16]: 
1990-04-01 25.870 
1990-04-02 26.205 
1990-04-03 12.283 
... 
+0

非常感谢 - 这就是我一直在寻找的! – user3018865