请考虑以下DateTimeIndex:

from calendar import monthrange
import pandas as pd

index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H')

我们可以看到,2022年1月和2023年1月都是不完整的.

如何创建包含该范围内完整的月/年的列表?

我一直在try 使用calendar中的monthrange来计算这些值,但不确定如何从下面开始:

years_months = index_h.to_period('M').unique()
complete_month_year_list = []
for year_month in years_months:
    num_days = monthrange(year_month.year, year_month.month)[1]
    if what_goes_here??? == num_days:    
        print(f"Month {year_month.month} of year {year_month.year} is complete.")
        complete_month_year_list.append(?????)
    else:
        print(f"Month {year_month.month} of year {year_month.year} is not complete.")

推荐答案

您可以通过判断该月的天数是否等于该月的总小时数来实现此目的.如果它们相等,则意味着该月已完成.

将该月的指数长度与该月的预期小时数进行比较.

from calendar import monthrange
import pandas as pd

index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H')

years_months = index_h.to_period('M').unique()
complete_month_year_list = []

for year_month in years_months:
    # Calculate the number of days in the month
    num_days = monthrange(year_month.year, year_month.month)[1]
    # Filter the index for the current month and year
    month_index = index_h[index_h.to_period('M') == year_month]
    # Check if the number of hours in the month is equal to the number of days in the month
    if len(month_index) == num_days * 24:
        print(f"Month {year_month.month} of year {year_month.year} is complete.")
        complete_month_year_list.append(year_month)
    else:
        print(f"Month {year_month.month} of year {year_month.year} is not complete.")

print("List of complete months:", complete_month_year_list)

Python相关问答推荐

Pandas 第二小值有条件

试图找到Python方法来部分填充numpy数组

使用索引列表列表对列进行切片并获取行方向的向量长度

使用@ guardlasses. guardlass和注释的Python继承

我如何根据前一个连续数字改变一串数字?

实现自定义QWidgets作为QTimeEdit的弹出窗口

如何在图中标记平均点?

如何启动下载并在不击中磁盘的情况下呈现响应?

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

如何在FastAPI中为我上传的json文件提供索引ID?

如何更改groupby作用域以找到满足掩码条件的第一个值?

如何在Great Table中处理inf和nans

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

计算机找不到已安装的库'

用fft计算指数复和代替求和来模拟衍射?

按条件添加小计列

Pandas在rame中在组内洗牌行,保持相对组的顺序不变,

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

如何在Python中自动创建数字文件夹和正在进行的文件夹?