Home:ALL Converter>Calculting log of lagged value of a column in pandas

Calculting log of lagged value of a column in pandas

Ask Time:2020-03-21T23:22:26         Author:Mehdi Zare

Json Formatter

I want to get the log of lagged value of a column divided by that column in pandas.

There's a simple way of doing this by adding a new column like this:

import pandas as pd
from numpy import log

df = pd.DataFrame({'reading': [2,3,4,5,6,7,8]})

df['lagged'] = df.reading.shift(1)
df['log'] = df.apply(lambda x: log(x['lagged']/ x['reading']), axis=1)

I'm wondering if there's a simpler way to do this without adding a new column.

Author:Mehdi Zare,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60789589/calculting-log-of-lagged-value-of-a-column-in-pandas
yy