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).
Let's Get in Touch
marketing@deepaiautomation.com
+91 6309397994
ยฉ 2025. All rights reserved.
Industries
Manufacturing
Financial Services
Retail
Solutions
DocuMind AI - Intelligent Document Migration
InsightEdge AI - Intelligent Power BI Reporting & Analytics
DCT AI - Digital Control Tower for Intelligent Enterprise Visibility
Inventra AI - Intelligent Inventory Optimization Platform
Maintenix AI - Predictive Maintenance Intelligence Platform
PayPredict AI - Intelligent Customer Payment Prediction Platform
SegMind AI - Intelligent Customer Segmentation & RFM Analytics Platform
DataForge AI - Intelligent ETL & Analytics Modernization Platform
DataSense AI - Intelligent Data Quality & Outlier Detection Agent
