# How do I find pairwise maximum of multiple rows in a column using python?

I have a column with float values. The column has 300 rows. I want to get the pairwise max of each row with the row below it. For example: if my column has 2, 25, 1, 24 as row values, I want to find max of 2 and 25, then max of 25 and 1 and so on. I also want to be able to create a new column with max values. How do I do it?

• In what context are these rows and columns? A pandas dataframe?
– noe
Jun 8, 2021 at 16:59
• yes, they are in a pandas dataframe Jun 8, 2021 at 17:23

This would be another approach a little bit shorter:

df.assign(resultado = lambda x: x.rolling(2).max())


EDIT:

def idx(x):
return x.index.values[np.argmax(x.values)]

df.rolling(2).agg(['max', idx])


will return both, the pairwise maximum and the index that corresponds to that value.

• how do I compare the last value to the first? Just so it has all values included Jun 8, 2021 at 19:06

You can create a new column like the one you have but "shifted" one position down, and the compute the maximum of these two columns:

import pandas as pd
import numpy as np

data = np.random.randint(0, 50, size=20)
df = pd.DataFrame(data, columns=['values'])
df['prev'] = df['values'].shift(1)
df['max'] = df[['values', 'prev']].max(axis=1)


The result is

+----+----------+--------+-------+
|    |   values |   prev |   max |
|----+----------+--------+-------|
|  0 |       17 |    nan |    17 |
|  1 |       32 |     17 |    32 |
|  2 |        3 |     32 |    32 |
|  3 |        4 |      3 |     4 |
|  4 |        4 |      4 |     4 |
|  5 |       17 |      4 |    17 |
|  6 |       12 |     17 |    17 |
...


You can then remove the first row if you don't need it.

• that's a great solution! thank you Jun 8, 2021 at 18:03
• what do I do if I need to print the row that is max of the two rows? Jun 8, 2021 at 18:05
• You can distinguish them with df['which'] = df['values'] - df['prev'] > 0 . These assigns True if the greatest value is the second row.
– noe
Jun 8, 2021 at 18:28