Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas reverse of diff()

I have calculated the differences between consecutive values in a series, but I cannot reverse / undifference them using diffinv():

ds_sqrt = np.sqrt(ds)
ds_sqrt = pd.DataFrame(ds_sqrt)
ds_diff = ds_sqrt.diff().values

How can I undifference this?

like image 484
Anesh Avatar asked Apr 18 '18 15:04

Anesh


People also ask

What is the opposite of diff Python?

The cumulative sum method has in fact the opposite effect of the . diff() method that you came across in chapter 1.

What does diff () do in pandas?

Pandas DataFrame diff() Method The diff() method returns a DataFrame with the difference between the values for each row and, by default, the previous row. Which row to compare with can be specified with the periods parameter.

How do you reverse a series in pandas?

Using loc() function to Reverse Row Reversing the rows of a data frame in pandas can be done in python by invoking the loc() function. The panda's dataframe. loc() attribute accesses a set of rows and columns in the given data frame by either a label or a boolean array.

What is diff () in Python?

diff(arr[, n[, axis]]) function is used when we calculate the n-th order discrete difference along the given axis. The first order difference is given by out[i] = arr[i+1] – arr[i] along the given axis. If we have to calculate higher differences, we are using diff recursively. Syntax: numpy.diff()


1 Answers

Reverse diff in one line with pandas

import pandas as pd

df = pd.DataFrame([10, 15, 14, 18], columns = ['Age'])
df['Age_diff'] = df.Age.diff()

df['reverse_diff'] = df['Age'].shift(1) + df['Age_diff']

print(df)

    Age  Age_diff  reverse_diff
0   10       NaN           NaN
1   15       5.0          15.0
2   14      -1.0          14.0
3   18       4.0          18.0  
like image 168
V Z Avatar answered Sep 16 '22 14:09

V Z