简体   繁体   中英

Python Pandas Cumulative Multiplication

I created a small dataframe and I want to multiply 0.5 to the previous row and so on.

In:

1
2
3
4

Out:

1
0.5
0.25
0.125

I tried the following but does not work the right way. It is not cumulative and let's say perpetual.

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

y[0] = 1
yd = pd.DataFrame(y)

k =  yd.shift(1) * 0.5

print (k)

Any idea? Thank you


2nd more complexed question based on previous issue.

data['y'] = np.where((data['a']<50) & (data['b']>0), data['initial'], pd.Series(0.99, data['y'].index).cumprod() / 0.99)

I tried this code but does not work. If the premises are true then call the 'initial' otherwise proceed to the cumulative multiplication.

Use numpy.power

np.power(.5, x - 1)

       0
0  1.000
1  0.500
2  0.250
3  0.125

Or as @DSM pointed out (more intuitively)

.5 ** (x - 1)

       0
0  1.000
1  0.500
2  0.250
3  0.125

On the other hand, if you just want strictly successive powers of .5

.5 ** pd.Series(range(len(x)))

0    1.000
1    0.500
2    0.250
3    0.125
dtype: float64

Another alternative with cumprod

pd.Series(.5, x.index).cumprod() / .5

0    1.000
1    0.500
2    0.250
3    0.125
dtype: float64

Or

pd.Series({**dict.fromkeys(range(4), .5), **{0: 1}}).cumprod()

0    1.000
1    0.500
2    0.250
3    0.125
dtype: float64

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