user6162407 user6162407 - 5 months ago 9
Python Question

New row based on other's row past value to current value

I'm trying to create a new column called

move
in
df
that gives the value of
1
if the value in
x is higher
than its previous value and a
0
if the
value is lower
, so the first value in
move
should be a
NaN
.

d = {'x': [1, 0, 2, 5, 4]}
df = pandas.DataFrame(d)


The column should look like this:

df['move'] = pandas.Series([NaN, 0, 1, 1, 0])

Answer

You can compare using shift with a slice of the column using iloc and cast the boolean series to numeric dtype using astype:

In [82]:
df['move'] = (df['x'].iloc[1:] > df['x'].iloc[1:].shift()).astype(int)
df

Out[82]:
   x  move
0  1   NaN
1  0   0.0
2  2   1.0
3  5   1.0
4  4   0.0

Note that the presence of NaN forces the dtype to be float here

Comments