I have a pandas dataframe. Write efficient code to find the index of the second highest…
- User
I have a pandas dataframe. Write efficient code to find the index of the second highest value in each row.
Assistant
Here is code to find the index of the second highest value in each row of a pandas dataframe:
pythondef second_highest(row): sorted_row = sorted(row, reverse=True) return row.index(sorted_row[1]) # Apply the function to each row df['second_highest'] = df.apply(second_highest, axis=1)This works by:
- Defining a function
second_highest()that takes a row as input - Sorting that row in descending order
- Taking the second element (index 1) from the sorted row, which will be the second highest value
- Defining a function
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.