在 pandas 中,直到给定 Timestamp 已经过了多少年的比例?
要计算自年初以来已过了多少年的比例,使用此函数:
fraction_of_year_passed.py
import pandas as pd
def fraction_of_year_passed(date):
"""计算到给定日期为止当前年份已经过了多少比例"""
start_of_year = pd.Timestamp(now.year, 1, 1)
start_of_next_year = pd.Timestamp(now.year + 1, 1, 1)
# 计算整年的秒数和自年初以来的秒数
entire_year_seconds = (start_of_next_year - start_of_year).total_seconds()
seconds_since_start_of_year = (date - start_of_year).total_seconds()
return seconds_since_start_of_year / entire_year_seconds使用示例:
fraction_of_year_passed.py
print(fraction_of_year_passed(pd.Timestamp("2020-03-01"))) # prints 0.16393442622950818详细说明:
首先,我们定义 date 所属日历年的开始,以及之后日历年的开始:
fraction_of_year_passed.py
start_of_year = pd.Timestamp(now.year, 1, 1)
start_of_next_year = pd.Timestamp(now.year + 1, 1, 1)现在我们计算整年的秒数和年初到 date 之间经过的秒数:
fraction_of_year_passed.py
entire_year_seconds = (start_of_next_year - start_of_year).total_seconds()
seconds_since_start_of_year = (date - start_of_year).total_seconds()其余很简单:只需将 seconds_since_start_of_year / entire_year_seconds 相除即可获得到 date 为止已过了多少年的比例。
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow