Pandas compare next row Pandas compare next row python python

Pandas compare next row


Looks like you want to use the Series.shift method.

Using this method, you can generate new columns which are offset to the original columns. Like this:

df['qty_s'] = df['qty'].shift(-1)df['t_s'] = df['t'].shift(-1)df['z_s'] = df['z'].shift(-1)

Now you can compare these:

df['is_something'] = (df['qty'] == df['qty_s']) & (df['t'] < df['t_s']) & (df['z'] == df['z_s'])

Here is a simplified example of how Series.shift works to compare next row to the current:

df = pd.DataFrame({"temp_celcius":pd.np.random.choice(10, 10) + 20}, index=pd.date_range("2015-05-15", "2015-05-24")) df            temp_celcius2015-05-15            212015-05-16            282015-05-17            272015-05-18            212015-05-19            252015-05-20            282015-05-21            252015-05-22            222015-05-23            292015-05-24            25df["temp_c_yesterday"] = df["temp_celcius"].shift(1)df            temp_celcius  temp_c_yesterday2015-05-15            21               NaN2015-05-16            28                212015-05-17            27                282015-05-18            21                272015-05-19            25                212015-05-20            28                252015-05-21            25                282015-05-22            22                252015-05-23            29                222015-05-24            25                29df["warmer_than_yesterday"] = df["temp_celcius"] > df["temp_c_yesterday"]            temp_celcius  temp_c_yesterday warmer_than_yesterday2015-05-15            21               NaN                 False2015-05-16            28                21                  True2015-05-17            27                28                 False2015-05-18            21                27                 False2015-05-19            25                21                  True2015-05-20            28                25                  True2015-05-21            25                28                 False2015-05-22            22                25                 False2015-05-23            29                22                  True2015-05-24            25                29                 False

If I misunderstood your query, please post a comment and I'll update my answer.