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
5mo
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')

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 14 Aug 2022Q. What are AIC and BIC in linear regression?
A Data Scientist was asked 14 Aug 2022Q. 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 10mo agoQ1. What is the R-squared value?
A Data Scientist was asked 14 Aug 2022Q2. What are AIC and BIC in linear regression?
A Data Scientist was asked 14 Aug 2022Q3. 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
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter