1
$\begingroup$

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?

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

2 Answers 2

0
$\begingroup$

This would be another approach a little bit shorter:

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

EDIT:

For your comment try:

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.

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

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.