you have a pandas dataframe with three columns, filled with state names, city names and arbitrary numbers respectively. How to retrieve top 2 cities per state. (top according to the max number in the third column)
AnswerBot
1y
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
22d
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
1y
df.groupby('state')['city', 'number'].nlargest(2, 'number')
Add answer anonymously...
Top Affine Data Scientist interview questions & answers
Popular interview questions of Data Scientist
Top HR questions asked in Affine Data Scientist
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app