简体   繁体   中英

Python Pandas Cumulative Multiplication with IF case

I created a small dataframe and I want to multiply 0.99 to the previous row and so on but only if the "IF case" is true, otherwise put the x[i].

In:

 1
 6
 2
 8
 4

Out:

    1.00
    0.99
    2.00
    1.98
    1.96

With a help from a guy, based on a similar problem, I tried the following but does not work.

x = pd.DataFrame([1, 6, 2, 8, 4])
y = np.zeros(x.shape)

yd = pd.DataFrame(y)
yd = np.where(x<3, x ,pd.Series(.99, yd.index).cumprod() / .99)

Any idea? Thank you

This is more like a groupby problem , when the value is less than 3 you reset the prod process

y=x[0]
mask=y<3
y.where(mask,0.99).groupby(mask.cumsum()).cumprod()
Out[122]: 
0    1.0000
1    0.9900
2    2.0000
3    1.9800
4    1.9602
Name: 0, dtype: float64

At least we have the for loop here (If above does not work )

your=[]
for t,v in enumerate(x[0]):
    if v < 3:
        your.append(v)
    else:
        your.append(your[t-1]*0.99)
your
Out[129]: [1, 0.99, 2, 1.98, 1.9602]

This checks whether the value of x in the current row is lesser than 3. If it is, it keeps it as is else multiplies the previous row by 0.99.

x = pd.DataFrame([1, 6, 2, 8, 4])   
x['out'] = np.where(x[0] <3, x[0], x[0].shift(1)*0.99)

Output:

x['out']

0    1.00
1    0.99
2    2.00
3    1.98
4    7.92

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM