为何to_datetime()会扭曲(压缩)原始密度函数形态?
生成指定密度年度时间戳的问题
需求与实现思路
- 目标:生成一年中符合特定密度分布的时间戳
- 实现思路:先定义期望的密度函数,将其拆分为差分步骤,再通过累加得到从年初开始的实际时间点
- 使用环境:当前为Anaconda Navigator + Jupyter Notebook,未来可能切换至VSCode
遇到的问题
- 原代码经
pd.to_datetime()处理后,得到的密度函数与原始形态差异明显,出现扭曲(压缩)情况 - 修改代码第23行
diff = 1 - act中的1为2后,曲线形态有所改善,但基线会从0跃升至最大值的一半,不符合需求
现有代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt # number of data points event_num = 50000 # desired density functions lin_up = np.linspace(0, 365, event_num) lin_down = lin_up[::-1] exp_up = np.exp(-lin_up / 100)[::-1] exp_down = np.exp(-lin_up / 100) harm_peak = 0.5 * (np.sin((lin_up / 58)-(np.pi/2)) + 1) harm_valley = 0.5 * (np.sin((lin_up / 58)+(np.pi/2)) + 1) ps_sigm_up = 0.5 * (np.sin((lin_up / 116)-(np.pi/2)) + 1) ps_sigm_down = 0.5 * (np.sin((lin_up / 116)+(np.pi/2)) + 1) act = harm_peak # so I don't have to manually update the actual function everywhere a_magsimum = np.max(act) # normalization 1 act = act/a_magsimum # normalization 2 # difference gives the steps (the smaller the difference, the larger the density) diff = 1 - act # here changeing the number changes the shape but the baseline too diff_magsimum = np.max(diff) # cumulative sum gives the actual days cum = np.cumsum(diff) cum_magsimum = np.max(cum) cum = 365 * cum/cum_magsimum plt.plot(act) plt.title("Desired density function") plt.show() plt.plot(diff) plt.title("Difference") plt.show() plt.plot(cum) plt.title("Cumulative sum") plt.show() # saving into CSV #df = pd.DataFrame({"Date": pd.to_datetime(cum, unit="D", origin="2024-01-01")}) #df.to_csv("events_new.csv", index=False) # dates daily (chatGPT) dates = pd.to_datetime(cum, unit="D", origin="2024-01-01").date density_per_day = pd.Series(dates).value_counts().sort_index() # dates weekly (chatGPT) #dates = pd.to_datetime(cum, unit="D", origin="2024-01-01") #density_per_week = dates.to_series().dt.to_period("W").value_counts().sort_index() # plotting graph - daily breakdown plt.plot(density_per_day.index, density_per_day.values, marker='o', linestyle='-') plt.xlabel("Date") plt.ylabel("Number of events / day") plt.title("Eventdensity by time") plt.xticks(rotation=45) plt.grid(True) plt.show() # plotting graph - weekly breakdown #plt.plot(density_per_week.index.astype(str), density_per_week.values, marker='o', linestyle='-') #plt.xlabel("Week") #plt.ylabel("Number of events / week") #plt.title("Weekly event density") #plt.xticks(rotation=45) #plt.grid(True) #plt.show()
内容的提问来源于stack exchange,提问作者PavelKorcsagin
相关产品推荐
相关产品推荐

