Home > OS >  is there any effective or efficient way to find net position of numbers from a data frame in python
is there any effective or efficient way to find net position of numbers from a data frame in python

Time:01-21

I have a multi index df, with column "Turtle"

|           |        | Turtle | Net Pos|
|-----------|--------|--------|--------|
|2004-11-04 |09:24   |6       |        |
|           |09:34   |2       |        |
|           |09:44   |0       |        |
|           |09:54   |4       |        |
|           |09:04   |1       |        |
|           |09:14   |2       |        |
|           |09:24   |9       |        |

turtle_factor = 3
base_quantity = 2

what I need is the "Net Pos". I couldn't figure out a way to do it elegantly. what I need is the col Net position using Numpy or Pandas The data set is huge, and need to use recursion and avoid crash.

Calculation

6 will be spilt in 6 times 1

1 1 1 1 1 1

first 1 will be multiplied base_quantity, so 1*2

second 1 will be multiplied with the result from first 1 with turtle factor 2*3

third 1 will be multiplied with the result from second 1 calculated multiplied with turtle factor above 6*3

forth one will be multiplied with the result from third 1 calculated multiplied with turtle factor above 18*3 and so on Summing them at the end to get the result as below for 1st row as 728

|           |        | Turtle | Net Pos|
|-----------|--------|--------|--------|
|2004-11-04 |09:24   |6       |    728 |
|           |09:34   |2       |      8 |
|           |09:44   |0       |      0 |
|           |09:54   |4       |     80 |
|           |09:04   |1       |      2 |
|           |09:14   |2       |      8 |
|           |09:24   |9       |  19682 |


CodePudding user response:

There is a simple formula that maps Turtle to Net Pos. The calculation can be expressed as a sum of geometric series times base_quantity, yielding the function f below.

turtle_factor = 3
base_quantity = 2

def f(n):
  return base_quantity * (turtle_factor ** n - 1) // (turtle_factor - 1)

df = pd.DataFrame({
    "Turtle": [6, 2, 0, 4, 1, 2, 9],
})
df["Net Pos"] = f(df.Turtle)
  •  Tags:  
  • Related