如何通过pandas python中日期记录的值增加日期范围?

时间:2015-09-26 07:03:51

标签: python pandas

让我说我有:

{"uid": 1111,
"from": "2015-11-07",
"to": "2015-12-31"}

日期范围如下:

DatetimeIndex(['2011-12-31', '2012-12-31', '2013-12-15', '2015-12-01',
               '2015-12-16'],
              dtype='datetime64[ns]', freq='A-DEC', tz=None)

我将DatetimeIndex转换为数据框。我想要实现的是当范围中存在日期时,将名为count的列增加1。对于此示例,以下日期应该增加:

'2015-12-01', '2015-12-16'

1 个答案:

答案 0 :(得分:2)

这是你想要的吗?

    In [1]: import pandas

    In [2]: index = pandas.DatetimeIndex(['2011-12-31', '2012-12-31', '2013-12-15', '2015-12-01', '2015-12-16'],
       ...: dtype='datetime64[ns]',  tz=None)

    In [3]: df = pandas.DataFrame(index=index)

    In [4]: df["count"] = 0

    In [5]: df.loc["2015-11-07":"2015-12-31"] += 1

    In [6]: df
    Out[6]: 
                count
    2011-12-31      0
    2012-12-31      0
    2013-12-15      0
    2015-12-01      1
    2015-12-16      1