ValueError: Wrong number of items passed 5, placement implies 1, error while finding the second max value in a row

Viewed 52

Obtaining the second maximum value for each row in a data frame, but getting value error

column = [col for col in dataframe.columns if '%' in col]

dataframe["Max_2nd"] = dataframe[column].apply(lambda row: row.nlargest(2).values[-1],axis=1)

How can I resolve this

1 Answers

So, given the following toy dataframe:

import pandas as pd

df = pd.DataFrame(
    (
        {
            "col1": [1, 2, 3, 4, 5, 6, 7, 8],
            "col2": [3, 0, 1, 3, 0, 1, 8, 5],
            "col3": [7, 9, 2, 6, 7, 8, 0, 1],
            "col4": [0, 4, 5, 0, 4, 3, 4, 0],
        }
    )
)

You can find the second max value in each row like this:

df["Max_2nd"] = df.apply(lambda x: sorted(x, reverse=True)[1], axis=1)

print(df)
# Outputs
   col1  col2  col3  col4  Max_2nd
0     1     3     7     0        3
1     2     0     9     4        4
2     3     1     2     5        3
3     4     3     6     0        4
4     5     0     7     4        5
5     6     1     8     3        6
6     7     8     0     4        7
7     8     5     1     0        5
Related