How can I iteratively compare the current line with the previous and next lines in Pandas?
2 answers
Here's how you can implement it for Series using rolling_apply
. It is not clear how your comparisons will work on a whole row in the DataFrame.
In [5]: s = Series([1,2,3,2,5])
In [6]: def f(rows):
if (rows[0] >= rows[1]) and (rows[2] >= rows[1]):
return (rows[0] + rows[2]) / 2
else:
return rows[1]
...:
In [7]: pd.rolling_apply(s, 3, f, center=True)
Out[7]:
0 NaN
1 2
2 3
3 4
4 NaN
dtype: float64
+3
source to share
I don't understand what operation you want to perform on strings, but the method shift
will work for you. (There are at Series.shift
and DataFrame.shift
.)
import pandas as pd import numpy as np np.random.seed(1) ser = pd.Series(np.random.random_integers(0,10,10)) shift_down_by_one = ser.shift(1) shift_up_by_one = ser.shift(-1) mask = (shift_up_by_one >= ser) & (shift_down_by_one >= ser) ser.loc[mask] = (shift_up_by_one + shift_down_by_one) / 2
+1
source to share