Reputation: 25
Let's say i have a dataframe:
Bob Ann
date
2002-10-30 09:00:00 1.0 1.1
2002-10-30 10:00:00 5.5 3.4
2002-10-30 12:00:00 5.5 5.4
2002-10-30 14:00:00 4.4 3.4
2002-10-30 16:00:00 4.3 0.4
... ... ...
2021-03-28 15:00:00 6.7 5.4
2021-03-28 16:00:00 6.5 4.8
2021-03-28 17:00:00 1.1 4.7
2021-03-28 18:00:00 6.7 4.8
2021-03-28 19:00:00 4.5 5.1
And i need to separate values from Bob and Ann by day (06:00 - 18:00) and night (18:01 - 05:59) in a boxplot (like this example in seaborn, but for values in day and night), how do i make a third column for the "hue" data? Is it better to add a flag as a third column? or do something else?
Thanks!
Upvotes: 0
Views: 72
Reputation: 11105
This is a great use case for df.between_time
(docs):
# Create example data
import numpy as np
import pandas as pd
np.random.seed(149)
df = pd.DataFrame(index=pd.date_range('2002-10-30 09:00:00',
'2002-11-01 09:00:00',
freq='2H'))
df['Bob'] = np.random.uniform(0, 5, size=len(df)).round(1)
df['Ann'] = np.random.uniform(0, 5, size=len(df)).round(1)
# Create a new column and label all rows as 'Night'
df['Time of Day'] = 'Night'
# Overwrite daytime rows with 'Day'.
# df.between_time includes both start and end times by default
df.loc[df.between_time('06:00', '18:00').index, 'Time of Day'] = 'Day'
# Print result
df
Bob Ann Time of Day
2002-10-30 09:00:00 4.4 3.0 Day
2002-10-30 11:00:00 4.9 1.0 Day
2002-10-30 13:00:00 4.3 1.3 Day
2002-10-30 15:00:00 4.2 4.7 Day
2002-10-30 17:00:00 4.5 3.6 Day
2002-10-30 19:00:00 4.3 3.6 Night
2002-10-30 21:00:00 2.4 1.5 Night
2002-10-30 23:00:00 2.2 0.4 Night
2002-10-31 01:00:00 3.0 2.8 Night
2002-10-31 03:00:00 0.3 3.5 Night
2002-10-31 05:00:00 2.1 1.5 Night
2002-10-31 07:00:00 4.5 3.6 Day
2002-10-31 09:00:00 0.6 2.3 Day
2002-10-31 11:00:00 4.6 0.2 Day
2002-10-31 13:00:00 1.0 4.3 Day
2002-10-31 15:00:00 0.8 1.2 Day
2002-10-31 17:00:00 4.8 3.2 Day
2002-10-31 19:00:00 4.9 2.5 Night
2002-10-31 21:00:00 3.8 0.4 Night
2002-10-31 23:00:00 4.5 3.3 Night
2002-11-01 01:00:00 2.9 0.6 Night
2002-11-01 03:00:00 4.3 4.3 Night
2002-11-01 05:00:00 0.6 5.0 Night
2002-11-01 07:00:00 4.5 0.3 Day
2002-11-01 09:00:00 3.0 1.1 Day
Upvotes: 1