2

I have a dataframe with 2 columns as below:

Index Year        Country
0     2015        US
1     2015        US
2     2015        UK
3     2015        Indonesia
4     2015        US
5     2016        India
6     2016        India
7     2016        UK

I want to create a new dataframe containing the maximum count of country in every year. The new dataframe will contain 3 columns as below:

    Index      Year      Country     Count
    0          2015      US          3
    1          2016      India       2

Is there any function in pandas where this can be done quickly?

3 Answers 3

1

One way can be to use groupby and along with size for finding in each category adn sort values and slice by possible number of year. You can try the following:

num_year = df['Year'].nunique()
new_df = df.groupby(['Year', 'Country']).size().rename('Count').sort_values(ascending=False).reset_index()[:num_year]

Result:

   Year   Country  Count
0  2015      US      3
1  2016   India      2
Sign up to request clarification or add additional context in comments.

Comments

0

Use:

1.

First get count of each pairs Year and Country by groupby and size. Then get index of max value by idxmax and select row by loc:


df = df.groupby(['Year','Country']).size()
df = df.loc[df.groupby(level=0).idxmax()].reset_index(name='Count')
print (df)
   Year Country  Count
0  2015      US      3
1  2016   India      2

2.

Use custom function with value_counts and head:

df = df.groupby('Year')['Country']
       .apply(lambda x: x.value_counts().head(1))
       .rename_axis(('Year','Country'))
       .reset_index(name='Count')

print (df)
   Year Country  Count
0  2015      US      3
1  2016   India      2

Comments

0

Just provide a method without groupby

Count=pd.Series(list(zip(df2.Year,df2.Country))).value_counts()
          .head(2).reset_index(name='Count')
Count[['Year','Country']]=Count['index'].apply(pd.Series)
Count.drop('index',1)


Out[266]: 
   Count  Year Country
0      3  2015      US
1      2  2016   India

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.