how to divide a row with the previous one and that the values remain in a new column?

Question:

My problem is that I have time series, and I need to create a new column that gives me the natural logarithm of today’s price divided by yesterday’s price, and that these values are in a new column

#Accion1['Rentabilidad1'] = Accion1.apply(lambda row: np.log(Promedio), axis=1)
Accion1['Rentabilidad'] = np.log(Accion1['Promedio'])
Accion1

enter image description here

I was thinking of creating new variables and splitting iloc[0]/iloc[1] but it doesn’t work either, please help ‍

Asked By: jomjac

||

Answers:

I would grab all of the previous dates and save them to a separate list:

fechas_anteriores = [x.strftime("%d-%m-%Y") for x in Accion1["Fecha anterior"]]

Then I would create a new column called Promedio anterior using .loc, making reference to fechas_anteriores:

Accion1["Promedio anterior"] = [fecha[0] if len(fecha) > 0 else None 
                                for fecha in [Accion1.loc[Accion1["Fecha de cotizacion"] == dt.strptime(fecha_anterior, "%d-%m-%Y")]["Promedio"].to_list() 
                                for fecha_anterior in fechas_anteriores]]

Finally I would execute the division:

Accion1["Division"] = Accion1["Rentabilidad"]/Accion1["Promedio anterior"]

You could do all of this in one line of course, though it would be less readable.

Answered By: David Smith