Home > front end >  how to calculate column based on a first value (pandas)(python)?
how to calculate column based on a first value (pandas)(python)?

Time:06-19

I has such a data frame using python pandas:

table

how can i calculate rest of the column dividing every new cell by 2?

so the result must be:

  • 0.05646
  • 0.02823
  • 0.014115

also this doesn't work: table['HAopen'][1:24] = (table['HAopen'].shift() )/2

CodePudding user response:

You can generate a list of 2^{index} and divide it by HAopen column

out = df['HAopen'].ffill().div(list(map(lambda x: pow(2,x), df.index)))
print(out)

0    0.056460
1    0.028230
2    0.014115
3    0.007058
4    0.003529
Name: HAopen, dtype: float64

CodePudding user response:

You can use numpy for efficiency:

import numpy as np
df['HAopen'].ffill().div(2**np.arange(len(df)))

output:

0    0.056460
1    0.028230
2    0.014115
3    0.007058
4    0.003529
5    0.001764
Name: HAopen, dtype: float64
  • Related