1

i have a dataframe like:

Company Date        Country
ABC     2017-09-17   USA
BCD     2017-09-16   USA
ABC     2017-09-17   USA
BCD     2017-09-16   USA
BCD     2017-09-16   USA

I want to get a resultant df as :

Company  No: of Days
ABC      2
BCD      3

How do i do it ?

0

1 Answer 1

3

You can use value_counts and rename_axis with reset_index:

df1 = df['Company'].value_counts()
                   .rename_axis('Company').reset_index(name='No: of Companies')
print (df1)
  Company  No: of Companies
0     BCD                 3
1     ABC                 2

Another solution with groupby and aggregating size, last reset_index:

df1 = df.groupby('Company').size().reset_index(name='No: of Companies')
print (df1)
  Company  No: of Companies
0     BCD                 3
1     ABC                 2

If need count Date columns:

df1 = df['Date'].value_counts().rename_axis('Date').reset_index(name='No: of Days')
print (df1)
         Date  No: of Days
0  2017-09-16            3
1  2017-09-17            2

df1 = df.groupby('Date').size().reset_index(name='No: of Days')
print (df1)
         Date  No: of Days
0  2017-09-16            3
1  2017-09-17            2

EDIT:

If need count pairs Date and Company columns:

df1 = df.groupby(['Date', 'Company']).size().reset_index(name='No: of Days per company')
print (df1)
         Date Company  No: of Days per company
0  2017-09-16     BCD                        3
1  2017-09-17     ABC                        2
Sign up to request clarification or add additional context in comments.

7 Comments

you are not at all using the 'date' column ?
@MohanRaj - I add solutions for date column, but then output is different.
I want only a dataframe which has only 2 columns in the result - company and date
@MohanRaj - yes. But it depends you need count column Company or column Dates. If my solution is not what you need, can you change sample data and add desired output?
Sorry, the i erred in the comment section - i needed only 2 columns - company and no_of_days_per_company.
|

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.