Skip to content
Advertisement

Get the sum of each column, with recursive values in each cell

Given a parameter p, be any float or integer.

For example, let p=4

time 1 2 3 4 5
Numbers a1 a1*(0.5)^(1/p)^(2-1) a1*(0.5)^(1/p)^(2-1) a1*(0.5)^(1/p)^(3-1) a1*(0.5)^(1/p)^(4-1)
Numbers nan a2 a2*(0.5)^(1/p)^(3-2) a2*(0.5)^(1/p)^(4-2) a2*(0.5)^(1/p)^(5-2)
Numbers nan nan a3 a3*(0.5)^(1/p)^(4-3) a3*(0.5)^(1/p)^(5-3)
Numbers nan nan nan a4 a4*(0.5)^(1/p)^(5-4)
Number nan nan nan nan a5
Final Results a1 sum of column 2 sum of column 3 sum of column 4 sum of column 5

Numbers like a1,a2,a3,a4,a5,…,at is given, our goal is to find the Final Results. Combining the answer provided by mozway, I wrote the following function which works well. It is a matrix way to solve the problem.

JavaScript

However, I don’t think this method will work well if we are dealing with large dataframe. Are there any better way to fix the problem? (In this case, faster = better.)

Advertisement

Answer

Assuming your number of rows is not too large, you can achieve this with numpy broadcasting:

First create a 2D array of factors:

JavaScript

Then map to your data and sum:

JavaScript

example output:

JavaScript

intermediate:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement