【问题标题】:Conditional Rolling Mean条件滚动平均值
【发布时间】:2020-01-29 01:42:04
【问题描述】:

您好,我有以下数据框:

import pandas as pd

df = pd.DataFrame()
df.index = ['2009-01-04', '2009-01-05', '2009-01-05', '2009-01-06', '2009-01-06', '2009-01-07', '2009-01-07', '2009-01-07']
df['score1'] = [84, 28, 38, 48, 23, 38, 22, 37]
df['score2'] = [83, 43, 12, 93, 64, 28, 29, 12]
df['score3'] = [92, 33, 11, 48, 23, 22, 12, 38]
df['score4'] = [43, 23, 41, 75, 93, 93, 23, 21]
df['condition1'] = [0, 0, 1, 0, 1, 0, 1, 0]
df['condition2'] = [1, 0, 1, 0, 0, 0, 0, 1]
df['condition3'] = [0, 0, 0, 1, 1, 0, 0, 1]

df = df.resample('D', how='mean')
df = df.rolling(30, min_periods=1).mean()

我想做一个超过 30 天的滚动平均值,但在满足“条件”之一(即条件 ==1)的行上超重。 IE。满足条件的行将极大地影响 30 天的时间范围。

有没有办法做到这一点?

【问题讨论】:

  • 你的“超重”是多少?
  • 例如,在 30 天的时间范围内,我会首先为有争议的行分配 30%。然后每天下降1%

标签: python pandas dataframe


【解决方案1】:

我不确定我是否理解,但您不能使用基于条件的加权分数来进行翻转吗?

extra_weight=2 # when condition is met, score is multiplied by extra_weight+1 

df['weighted_score1']=df['score1']*(df['condition1']*extra_weight+1) # we add 1 so that score is counted even when condition == 0
#repeat for score2 and 3
df = df.rolling(30, min_periods=1).mean() 

更新以回答评论:根据多个条件应用权重。

在您的条件列中,您只有 1 和 0。 要满足两列之间的 AND 条件,您可以取最小值。事实上,如果两列都是 1,你得到 1,如果一列或两列都是 0,你得到 0。 同样,要满足 OR 条件,您可以取最大值。

例如,如果您想为(condition1 AND condition2) OR condition3 添加额外的权重:

import numpy as np
df['final_cond']= np.maximum(np.minimum(df['condition1'],df['condition2']),df['condition3'])

df['weighted_score1']=df['score1']*(df['final_cond']*extra_weight+1)

【讨论】:

  • 我喜欢这个想法,但它不仅适用于条件 1... 它可能是条件 1 和/或条件 2 和/或条件 3。你会如何调整这个?
  • 你的意思是只有一个条件可以影响一行?那么,如果 condition1 和 condition2 都连续为 1,那么只会应用一个权重?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2018-03-08
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多