Minus infinity in Python as a result of for loop?

Question:

I am trying to calculate valocity in Python with for loop. But when I run my code, I get "-inf" as a result for every row.

This is my code:

Vx = 0
for i in range(1, len(x_axis.timestamp)):
    Vx += Vx + (x_axis.diff_ts[i]) * float(x_axis.value_x[i-1])
    x_axis['Vx'] = Vx
print(x_axis)

Vx is my new column. I am not sure what I am doing wrong.

When I check dtypes, I get this:

timestamp           float64
value_x              object
y_axis              float64
z_axis              float64
diff_ts             float64

My data looks like:

        timestamp          value_x  ...  lag(timestamp,1)  diff_ts
0     1.661847e+09     -8.579621315  ...      0.000000e+00    0.000
1     1.661847e+09  -8.586804389953  ...      1.661847e+09    0.020
2     1.661847e+09   -8.56884765625  ...      1.661847e+09    0.020
3     1.661847e+09     -8.579621315  ...      1.661847e+09    0.020
4     1.661847e+09   -8.58800125122  ...      1.661847e+09    0.021

Reproducible example:

import pandas as pd

data = {'timestamp': [1.661848e+09, 1.661848e+09, 1.661848e+09, 1.661848e+09, 1.661848e+09],
        'value_x': [-8.56884765625, -8.573636055, -8.58201599121, -8.565256118774, -8.58201599121],
        'diff_ts': [0.000, 0.020, 0.021, 0.020, 0.020]
        }

df = pd.DataFrame(data)
df['value_x'] = df['value_x'].astype(object, errors='raise')
print(df.info())
print(df)

Vx = 0
for i in range(1, len(df.timestamp)):
    Vx = Vx + (df.diff_ts[i]) * float(df.value_x[i-1])
    df['Vx'] = Vx
print(df)
Asked By: Eva

||

Answers:

df['Vx'] = Vx will set Vx as value for the whole column.
So if at the last iteration Vx = -inf, the column will have -inf at every row.

You can use df.at[<row>, <col>] = <val> to set a single value at (<row>, <col>) position.

As @Paul Hankin mentioned in the comments, the += in Vx += Vx + (x_axis.diff_ts[i]) * float(x_axis.value_x[i-1]) might result in -inf at some point if the number of iteration is high enough.

By the way, there is a mismatch between the first code snippet and the reproducible example, since in the latter you don’t use the +=.

Try using at as mentioned above and Vx = Vx + ... instead of Vx += Vx ... and see if you still encounter the same issue.

Answered By: el_gio
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.