仅当窗口有超过x个可用数据时使用滚动函数查找平均值

2024-06-16 13:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框架df,它包含诸如日期、公司名称、独立价格、合并价格等列

我想在一个条件下找出过去10年价格列的平均值

如果price_consolidated有过去10年的数据(即非NaN),则price_consolidated列的数据将被使用,其他price_standalone的数据将被使用

df["Price mean 10 years"] = df.groupby('Company Name')["price_consolidated"].shift().rolling(min_periods=1, window=3650).mean()

这就是我计算平均数的方法。有人能帮我处理代码的条件部分吗? 如有可能,还应在其旁边另加一列,说明是否使用price_consolidated或price_standalone

例如,日期时间索引为31-12-2010的行将根据2000年12月31日至2010年12月31日的合并价格计算平均值(如果所有数据可用),否则将根据价格计算平均值

在图像中,第一次出现的日期已经在计算中,因此无需担心。 sample output

Thx

date1 = '31/03/2020'
date2 = '31/03/2010'
date1 = pd.to_datetime(date1)
date2 = pd.to_datetime(date2)
if(df_dates2.iloc[date1, 'First Occurence Consolidated']<date2):
    print(1) #find mean by consolidated data
else:
    print(2) #find mean by standalone data

这会产生以下错误:ValueError:基于位置的索引只能有[integer,integer slice(包括起点,不包括终点),listlike of integer,boolean array]类型


Tags: to数据dfdatetime价格integermean条件