You have a pandas dataframe with three columns filled with state names, city names, and arbitrary numbers, respectively. How do you retrieve the top two cities per state based on the maximum number in the third column?

AnswerBot
2y

Retrieve top 2 cities per state based on max number in third column of pandas dataframe.

  • Group the dataframe by state column

  • Sort each group by the third column in descending order

  • Retrieve the top 2 row...read more

Bikash Debnath
6mo
import pandas as pd # Create a sample DataFrame data = { "State": ["California", "California", "California", "Texas", "Texas", "Texas", "New York", "New York", "New York"], "City": ["Los Angeles", "Sa...read more
Paras Chaudhary
2y

df.groupby('state')['city', 'number'].nlargest(2, 'number')

Select
Add answer anonymously...

Affine Data Scientist interview questions & answers

A Data Scientist was asked 10mo agoQ. What is the R-squared value?
A Data Scientist was asked Q. What are AIC and BIC in linear regression?
A Data Scientist was asked Q. What is the purpose of a lambda function when regular functions exist? How are t...read more

Popular interview questions of Data Scientist

A Data Scientist was asked 11mo agoQ1. What is the R-squared value?
A Data Scientist was asked Q2. What are AIC and BIC in linear regression?
A Data Scientist was asked Q3. What is the purpose of a lambda function when regular functions exist? How are t...read more
Affine Data Scientist Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits