Date column of the Dataframe

Asked

Viewed 6,739 times

1

I have this Dataframe and would like to separate the column from the date as I do it?

    Data e Hora         Consumo(litros)  Valor Acumulado
0   2017-08-21 20:00:00              65               65
1   2017-08-21 21:00:00              81              146
2   2017-08-21 22:00:00              10              156
  • 2

    What you want to do is take only the column date Date and Time ? Or just take the whole column? Have you tried doing what you want ? Edith your question and put the code.

  • I would like to first separate the date and time column and turn into two columns.

1 answer

4


First you must turn the column Data e Hora for datetime

df['Data e Hora'] = pd.to_datetime(df['Data e Hora'])

to create the columns using the method dt.strftime convert the column value Data e Hora for a string in date format.

# Coluna 'Data'
df['Data'] = df['Data e Hora'].dt.strftime('%Y-%m-%d')
# Coluna 'Hora'
df['Hora'] = df['Data e Hora'].dt.strftime('%H:%M:%S')

now has the result:

          Data e Hora  Consumo(litros)    ...           Data      Hora
0 2017-08-21 20:00:00               65    ...     2017-08-21  20:00:00
1 2017-08-21 21:00:00               81    ...     2017-08-21  21:00:00
2 2017-08-21 22:00:00               10    ...     2017-08-21  22:00:00

If you want to remove the column Data e Hora and sort the columns by placing the column Data and the column Hora at first:

# Remove a coluna 'Data e Hora'
del df['Data e Hora']
# Ordena as colunas
df = df[['Data', 'Hora', 'Consumo(litros)', 'Valor Acumulado']]

The result now is:

         Data      Hora  Consumo(litros)  Valor Acumulado
0  2017-08-21  20:00:00               65               65
1  2017-08-21  21:00:00               81              146
2  2017-08-21  22:00:00               10              156

See working on repl.it

The complete code:

import pandas as pd
df = pd.read_csv('DataFrame.csv', delimiter=";");

df['Data e Hora'] = pd.to_datetime(df['Data e Hora'])
df['Data'] = df['Data e Hora'].dt.strftime('%Y-%m-%d')
df['Hora'] = df['Data e Hora'].dt.strftime('%H:%M:%S')

del df['Data e Hora']
df = df[['Data', 'Hora', 'Consumo(litros)', 'Valor Acumulado']]

print(df)

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.