Agregar una columna que es el resultado de la diferencia en filas consecutivas en pandas


Digamos que tengo un dataframe como este

    A   B
0   a   b
1   c   d
2   e   f 
3   g   h

0,1,2,3 son tiempos, a, c, e, g es una serie de tiempo y b, d, f, h es otra serie de tiempo. Necesito poder agregar dos columnas al dataframe original que se obtiene computando las diferencias de filas consecutivas para ciertas columnas.

Así que necesito algo como esto

    A   B   dA
0   a   b  (a-c)
1   c   d  (c-e)
2   e   f  (e-g)
3   g   h   Nan

Vi algo llamado diff en el dataframe/series pero eso lo hace ligeramente diferente ya que en el primer elemento se convertirá en Nan.

Author: AMM, 2014-04-18

2 answers

Use shift.

df['dA'] = df['A'] - df['A'].shift(-1)
 72
Author: exp1orer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-17 20:43:31

Puedes usar diff y pasar -1 como el argumento periods:

>>> df = pd.DataFrame({"A": [9, 4, 2, 1], "B": [12, 7, 5, 4]})
>>> df["dA"] = df["A"].diff(-1)
>>> df
   A   B  dA
0  9  12   5
1  4   7   2
2  2   5   1
3  1   4 NaN

[4 rows x 3 columns]
 31
Author: DSM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-17 20:45:00