Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Groupby Name of Day

Tags:

python

pandas

I have a dataset that includes a date time field called 'pub_date.'

In [69]: dataset[['pub_date']].dtypes

Out[69]: pub_date datetime64[ns]
         dtype: object

I'm trying to group the dataset by the name of the day (e.g. Mon, Tue, ... , Sat, Sun) to no avail. My approach so far has been to create fields for all the different ways I might group the data. So I've been able to get year, month, day, etc., by doing the following:

dataset['year'] = [t.year for t in dataset.pub_date]
dataset['month'] = [t.month for t in dataset.pub_date]
dataset['day'] = [t.day for t in dataset.pub_date]

The last thing I need is to get a field with 'day_name' so I can group it and plot it, but I can't figure out a way to do this. I appreciate any pointers you might be able to provide. Thank you!

like image 777
JeffyTwoTimes Avatar asked Dec 20 '25 23:12

JeffyTwoTimes


1 Answers

You can do the following:

df['day_name'] = df['pub_date'].apply(
    lambda x: pd.to_datetime(x).strftime("%A"))

This will give you a field that you can then easily group and plot.

enter image description here

like image 196
Bill Avatar answered Dec 22 '25 15:12

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!