How to group and count the number of people visits in particular year and months

Viewed 132

I have a Dataset with personal data such as Date and Total Visits. I would build a graph with number of people visits in Particular Year or particular month. I'm using python pandas to accomplish this and my strategy but not able to get this.

2 Answers

Make Columns for Month-year and Year, and use groupby

You can try following:

import pandas as pd
import datetime as dt
#Get Month end date 
df['month_end'] = df['date'].apply(lambda x: pd.Period(x,freq='M').end_time.date().strftime('%Y-%m-%d'))

df_agg = df.groupby(['month_end'])['Total Visits'].sum().reset_index()

df_agg will have visits aggregated by month end date.

Use following to create bar plot

import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={'figure.figsize':(11.7,8.27)})
# Set Seaborn style
sns.set_style('darkgrid')


# Construct plot
sns.barplot(x = "month_end", y = "Total Visits", data = df_agg)
plt.xticks(rotation=45)
plt.show()

enter image description here

Related