Assign day time to hours

0

I have the following df:

df = pd.DataFrame({'hora completa':['21:35:00', '22:16:00', '00:50:00', '09:30:00', '14:30:00']})
print(df)
  hora completa
0      21:35:00
1      22:16:00
2      00:50:00
3      09:30:00
4      14:30:00

I need to create a 'period' column with the criteria:

- Madrugada: Entre 00:00 e 05:59
- Manhã: Entre às 06:00 e 11:59
- Tarde: Entre o 12:00 e 17:59
- Noite: Entre às 18:00 e 23:59

I tried to solve using numpy, like this:

mask1 = df['hora completa'].between('06:00:00', '11:59:00')
mask2 = df['hora completa'].between('12:00:00', '17:59:00')
mask3 = df['hora completa'].between('18:00:00', '23:59:00')
mask4 = df['hora completa'].between('00:00:00', '05:59:00')

df['periodo'] = np.where(mask1, 'Manhã', 
                         mask2, 'Tarde', 
                         mask3, 'Noite', 
                         mask4, 'Madrugada')

print (df)

But give the error below:

TypeError: where() takes at most 3 arguments (8 given)

What am I missing? Is it possible to make a def with if and else ?

    
asked by anonymous 14.06.2018 / 05:59

1 answer

1

The message that the where function receives at most 3 arguments, and you are reporting 8! You can use the apply function and report as parameters, a function that will be executed for each item and axis :

import pandas as pd

def periodo(linha):
  horario = linha['hora completa']
  if '06:00:00' < horario < '11:59:00': return 'Manha'
  elif '12:00:00' < horario < '17:59:00': return 'Tarde'
  elif '18:00:00' < horario < '23:59:00': return 'Noite'
  elif '00:00:00' < horario < '05:59:00': return 'Madrugada'
  return ''

df = pd.DataFrame({'hora completa':['21:35:00', '22:16:00', '00:50:00', '09:30:00', '14:30:00']})
df['periodo'] = df.apply(periodo, axis=1)
print(df)

Output:

  hora completa    periodo
0      21:35:00      Noite
1      22:16:00      Noite
2      00:50:00  Madrugada
3      09:30:00      Manha
4      14:30:00      Tarde

See working at repl.it and also I created a Gist in GitHubGist

Reference

14.06.2018 / 07:12