Pandas Trick-2: Extracting First and Second Maximum Values from Each Row in a Pandas DataFrame
PANDAS
7/21/20251 min read
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
'A': [5, 1, 3],
'B': [2, 8, 7],
'C': [9, 4, 6]
})
# Get first and second max values for each row
top_2 = df.apply(lambda row: row.nlargest(2).values, axis=1)
# Convert to DataFrame
top_2_df = pd.DataFrame(top_2.tolist(), columns=['First_Max', 'Second_Max'])
# Concatenate with original DataFrame (optional)
result = pd.concat([df, top_2_df], axis=1)
print(result)


Notes:
row.nlargest(2).values gives you a NumPy array of top 2 values in descending order.
This works row-wise (axis=1).