将彼此在某个时间范围内的任意日期对象分组在一起

发布于 2024-09-13 10:49:04 字数 671 浏览 13 评论 0原文

我想将日历分割为从 2008-May-5 开始的两周间隔,或任何任意起点。

因此,我从几个日期对象开始:

import datetime as DT

raw = ("2010-08-01",
       "2010-06-25",
       "2010-07-01",
       "2010-07-08")

transactions = [(DT.datetime.strptime(datestring, "%Y-%m-%d").date(),
                 "Some data here") for datestring in raw]
transactions.sort()

通过手动分析日期,我非常能够找出哪些日期属于同一两周间隔。我想要得到与此类似的分组:

# Fortnight interval 1
(datetime.date(2010, 6, 25), 'Some data here')
(datetime.date(2010, 7, 1), 'Some data here')
(datetime.date(2010, 7, 8), 'Some data here')

# Fortnight interval 2
(datetime.date(2010, 8, 1), 'Some data here')

I want to split the calendar into two-week intervals starting at 2008-May-5, or any arbitrary starting point.

So I start with several date objects:

import datetime as DT

raw = ("2010-08-01",
       "2010-06-25",
       "2010-07-01",
       "2010-07-08")

transactions = [(DT.datetime.strptime(datestring, "%Y-%m-%d").date(),
                 "Some data here") for datestring in raw]
transactions.sort()

By manually analyzing the dates, I am quite able to figure out which dates fall within the same fortnight interval. I want to get grouping that's similar to this one:

# Fortnight interval 1
(datetime.date(2010, 6, 25), 'Some data here')
(datetime.date(2010, 7, 1), 'Some data here')
(datetime.date(2010, 7, 8), 'Some data here')

# Fortnight interval 2
(datetime.date(2010, 8, 1), 'Some data here')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花伊自在美 2024-09-20 10:49:04
import datetime as DT
import itertools

start_date=DT.date(2008,5,5)

def mkdate(datestring):
    return DT.datetime.strptime(datestring, "%Y-%m-%d").date()

def fortnight(date):
    return (date-start_date).days //14

raw = ("2010-08-01",
       "2010-06-25",
       "2010-07-01",
       "2010-07-08")
transactions=[(date,"Some data") for date in map(mkdate,raw)]
transactions.sort(key=lambda (date,data):date)

for key,grp in itertools.groupby(transactions,key=lambda (date,data):fortnight(date)):
    print(key,list(grp))

# (55, [(datetime.date(2010, 6, 25), 'Some data')])
# (56, [(datetime.date(2010, 7, 1), 'Some data'), (datetime.date(2010, 7, 8), 'Some data')])
# (58, [(datetime.date(2010, 8, 1), 'Some data')])

注意,2010-6-25 是自 2008-5-5 以来的第 55 个两周,而 2010-7-1 是第 56 个两周。如果您希望将它们组合在一起,只需更改 start_date(更改为 2008-5-16 之类的值)。

附言。上面用到的关键工具是itertools.groupby,详细解释这里

编辑:lambda只是一种使“匿名”的方法功能。 (它们是匿名的,因为它们没有像 def 定义的函数那样被赋予名称)。在任何地方看到 lambda 时,都可以使用 def 创建等效函数。例如,您可以这样做:

import operator
transactions.sort(key=operator.itemgetter(0))

def transaction_fortnight(transaction):
    date,data=transaction
    return fortnight(date)

for key,grp in itertools.groupby(transactions,key=transaction_fortnight):
    print(key,list(grp))
import datetime as DT
import itertools

start_date=DT.date(2008,5,5)

def mkdate(datestring):
    return DT.datetime.strptime(datestring, "%Y-%m-%d").date()

def fortnight(date):
    return (date-start_date).days //14

raw = ("2010-08-01",
       "2010-06-25",
       "2010-07-01",
       "2010-07-08")
transactions=[(date,"Some data") for date in map(mkdate,raw)]
transactions.sort(key=lambda (date,data):date)

for key,grp in itertools.groupby(transactions,key=lambda (date,data):fortnight(date)):
    print(key,list(grp))

yields

# (55, [(datetime.date(2010, 6, 25), 'Some data')])
# (56, [(datetime.date(2010, 7, 1), 'Some data'), (datetime.date(2010, 7, 8), 'Some data')])
# (58, [(datetime.date(2010, 8, 1), 'Some data')])

Note that 2010-6-25 is in the 55th fortnight from 2008-5-5, while 2010-7-1 is in the 56th. If you want them grouped together, simply change start_date (to something like 2008-5-16).

PS. The key tool used above is itertools.groupby, which is explained in detail here.

Edit: The lambdas are simply a way to make "anonymous" functions. (They are anonymous in the sense that they are not given names like functions defined by def). Anywhere you see a lambda, it is also possible to use a def to create an equivalent function. For example, you could do this:

import operator
transactions.sort(key=operator.itemgetter(0))

def transaction_fortnight(transaction):
    date,data=transaction
    return fortnight(date)

for key,grp in itertools.groupby(transactions,key=transaction_fortnight):
    print(key,list(grp))
雾里花 2024-09-20 10:49:04

使用带有 lambda 函数的 itertools groupby 将距起点的距离除以周期长度。

>>> for i, group in groupby(range(30), lambda x: x // 7):
    print list(group)


[0, 1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12, 13]
[14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27]
[28, 29]

对于日期:

import itertools as it
start = DT.date(2008,5,5)
lenperiod = 14

for fnight,info in it.groupby(transactions,lambda data: (data[0]-start).days // lenperiod):
    print list(info)

您还可以使用 strftime 中的周数,以及周数中的 lenperiod :

for fnight,info in it.groupby(transactions,lambda data: int (data[0].strftime('%W')) // lenperiod):
    print list(info)

Use itertools groupby with lambda function to divide by the length of period the distance from starting point.

>>> for i, group in groupby(range(30), lambda x: x // 7):
    print list(group)


[0, 1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12, 13]
[14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27]
[28, 29]

So with dates:

import itertools as it
start = DT.date(2008,5,5)
lenperiod = 14

for fnight,info in it.groupby(transactions,lambda data: (data[0]-start).days // lenperiod):
    print list(info)

You can use also weeknumbers from strftime, and lenperiod in number of weeks:

for fnight,info in it.groupby(transactions,lambda data: int (data[0].strftime('%W')) // lenperiod):
    print list(info)
橘香 2024-09-20 10:49:04

使用 pandas DataFrame 和 < a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling" rel="nofollow">resample 也可以。给定OP的数据,但将“此处的一些数据”更改为“abcd”。

>>> import datetime as DT
>>> raw = ("2010-08-01",
...        "2010-06-25",
...        "2010-07-01",
...        "2010-07-08")
>>> transactions = [(DT.datetime.strptime(datestring, "%Y-%m-%d"), data) for
...                 datestring, data in zip(raw,'abcd')]
[(datetime.datetime(2010, 8, 1, 0, 0), 'a'),
 (datetime.datetime(2010, 6, 25, 0, 0), 'b'),
 (datetime.datetime(2010, 7, 1, 0, 0), 'c'),
 (datetime.datetime(2010, 7, 8, 0, 0), 'd')]

现在尝试使用熊猫。首先创建一个 DataFrame,命名列并将索引设置为日期。

>>> import pandas as pd
>>> df = pd.DataFrame(transactions,
...                   columns=['date','data']).set_index('date')
           data
date
2010-08-01    a
2010-06-25    b
2010-07-01    c
2010-07-08    d

现在开始每 2 周使用一次系列偏移别名周日并连接结果。

>>> fortnight = df.resample('2W-SUN').sum()
           data
date
2010-06-27    b
2010-07-11   cd
2010-07-25    0
2010-08-08    a

需要钻取数据

>>> fortnight.loc['2010-06-27']['data']
b

现在根据周开始或

>>> fortnight.iloc[0]['data']
b

指数的

>>> data = fortnight.iloc[:2]['data']
b
date
2010-06-27     b
2010-07-11    cd
Freq: 2W-SUN, Name: data, dtype: object
>>> data[0]
b
>>> data[1]
cd

Using a pandas DataFrame with resample works too. Given OP's data, but change "some data here" to 'abcd'.

>>> import datetime as DT
>>> raw = ("2010-08-01",
...        "2010-06-25",
...        "2010-07-01",
...        "2010-07-08")
>>> transactions = [(DT.datetime.strptime(datestring, "%Y-%m-%d"), data) for
...                 datestring, data in zip(raw,'abcd')]
[(datetime.datetime(2010, 8, 1, 0, 0), 'a'),
 (datetime.datetime(2010, 6, 25, 0, 0), 'b'),
 (datetime.datetime(2010, 7, 1, 0, 0), 'c'),
 (datetime.datetime(2010, 7, 8, 0, 0), 'd')]

Now try using pandas. First create a DataFrame, naming the columns and setting the indices to the dates.

>>> import pandas as pd
>>> df = pd.DataFrame(transactions,
...                   columns=['date','data']).set_index('date')
           data
date
2010-08-01    a
2010-06-25    b
2010-07-01    c
2010-07-08    d

Now use the Series Offset Aliases to every 2 weeks starting on Sundays and concatenate the results.

>>> fortnight = df.resample('2W-SUN').sum()
           data
date
2010-06-27    b
2010-07-11   cd
2010-07-25    0
2010-08-08    a

Now drill into the data as needed by weekstart

>>> fortnight.loc['2010-06-27']['data']
b

or index

>>> fortnight.iloc[0]['data']
b

or indices

>>> data = fortnight.iloc[:2]['data']
b
date
2010-06-27     b
2010-07-11    cd
Freq: 2W-SUN, Name: data, dtype: object
>>> data[0]
b
>>> data[1]
cd
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文