Skip to main content
 首页 » 编程设计

python之Pandas 数据框中一个月的第一个和最后一个可用数据点

2025年05月04日7lautakyan007

在每个月的月初和月末,我需要在 python 中执行特定的计算。问题是我不能使用像这样的函数:

def first_day_of_year(d): 
    return date(d.year, 1) 

因为我使用的数据框没有一年中每一天的数据点。那么如何调用一个月的第一个可用数据点呢?我如何调用最后一个?

请您参考如下方法:

假设您有一个 datetime 对象列表,并且您希望按 .month 属性对它们进行分组。因此,首先您需要对它们进行排序,然后您可以应用 itertools.groupby() 函数,该函数返回:一个组值和一个迭代器。

import itertools 
 
#Your datetime objects 
dates = [] 
 
dates.sort() 
 
groups = itertools.groupby(time_obj_dates, key = lambda x:x.month) 
 
for mon, dates in groups: 
    for date in dates: 
        print mon, ("-".join(map(str,[date.year, date.month, date.day]))) 
 
>>> 1 1980-1-1 
    1 1980-1-2 
    1 1980-1-3 
    1 1980-1-4 
    1 1980-1-7 

因此,您从输出中看到我们根据月份对日期进行了分组。我们已经对列表进行了排序,因此,为了获得开始日期,我们选择了 group 中的第一个元素,而对于最后日期,我们选择了该组的结束元素。

要访问给定组的开始和结束日期,您可以使用:

for mon,dates in groups: 
   list_dates = list(dates) 
   print mon, list_dates[0], list_dates[-1]