Loop in Python to find the max value of every destiny

Viewed 56

I am fairly new in python. I am working with the nycflights13 df.

My goal is to determine the most common and least common origin for every destiny.

+---------+--------------------+-----------+---------------------+------------+
| destiny | most_common_origin | max_count | least_common_origin |  min_count |
+---------+--------------------+-----------+---------------------+------------+
| MIA     | LGA                |      5781 | EWR                 |       2633 |
+---------+--------------------+-----------+---------------------+------------+

I managed to do it for one destiny but I´m having trouble in the loop and also the binding the rows because sometimes I get a series.

My working example

from nycflights13 import flights

flights_to_MIA = flights[flights['dest']=='MIA']
flights_to_MIA.groupby(flights_to_MIA['origin']).size().reset_index(name='counts')

Note that I used size and then reset.index to make it a df.

1 Answers

You may check agg + value_counts

s=df.groupby('dest').agg(most_common_origin=('origin',lambda x : x.mode()[0]),
                              max_count=('origin',lambda x : x.value_counts().sort_values().iloc[-1]),
                              least_common_origin=('origin',lambda x : x.value_counts().sort_values().iloc[[0]].index),
                              min_count=('origin',lambda x : x.value_counts().sort_values().iloc[0]))
Related