Python Pandas Cumprod 问题

标签 python pandas dataframe

我仍然在努力处理以下代码:

xa= [0, 0, 0, 0, 65, 67, 69, 75, 0, 0, 0]
xb = [.3, .3, .3,.3, .3, .3, .3, .3, .3, .3, .3]
ideal = [0, 0, 0, 0, 65, 67, 69, 75, 67.5, 60.75, 54.675]

df = pd.DataFrame({'a':xa, 'b':xb, 'i':ideal})

mask=(df['a']<51) & (df['b']>0)
df['c'] = df['a'].where(mask,0.9).groupby(~mask.cumsum()).cumprod()

print(df)

我希望“c”列变得像“理想”。这只是我的 10 万多行完整数据集的一个示例。

'mask' 的计算方式如下: 当 'a'{i}<51 且 'b'{i}>0 时?那么为真,否则为假

'c' 列的计算方式如下: 当 'mask'{i}=FALSE 时 'c'{i}='a'{i} 否则 'c'{i}=0.9*'c'{i-1}

所以我希望(有一天)“c”变得像“理想”......

最佳答案

我相信这可以解决您的问题:

# First calculate the column as if there is no decay
mask=(df['a']<51) & (df['b']>0)
df['c'] = df['a'].where(~mask)
df['c'].fillna(method='ffill', inplace=True)
df['c'].fillna(0, inplace=True)

# Check how many rows since the mask has changed from True to False or v.v.
df['ones'] = 1
df['power'] = df['ones'].groupby((mask != mask.shift()).cumsum()).transform('cumsum')
# For the values in the mask, apply the decay
df['c'] = np.where(mask, 0.9 ** df['power']*df['c'], df['c'])
print(df)

输出:

     a    b       i       c  power ones
0    0  0.3   0.000   0.000       1     1
1    0  0.3   0.000   0.000       2     1
2    0  0.3   0.000   0.000       3     1
3    0  0.3   0.000   0.000       4     1
4   65  0.3  65.000  65.000       1     1
5   67  0.3  67.000  67.000       2     1
6   69  0.3  69.000  69.000       3     1
7   75  0.3  75.000  75.000       4     1
8    0  0.3  67.500  67.500       1     1
9    0  0.3  60.750  60.750       2     1
10   0  0.3  54.675  54.675       3     1

主要技巧是定义一列,定义乘以 0.9 的次数,另一列向前填充,以检查如果没有衰减的话,数字会是多少。希望这有帮助!

关于Python Pandas Cumprod 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52355289/

相关文章:

R Split data.frame 使用代表和开/关开关的列

python - 如果将最小的正浮点值乘以一个非零数,是否保证得到非零结果?

python - 基本的 Python 导入问题

python - 如何在 Pandas 中读取固定宽度格式的文本文件?

python - 如何从 Pandas 数据框中的当前行中减去前一行并将其应用于每一行;不使用循环?

python - 计算时间序列中的最高连续值

python - 有条件地填充数据框列的所有后续值

Python 光线追踪

python - 在 Python 中绘制具有平滑外观的时间序列的导数

python - Pandas 选择过去最近的日期