Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas convert index to datetime

Tags:

python

pandas

How do i convert a pandas index of strings to datetime format

my dataframe 'df' is like this

                     value           2015-09-25 00:46    71.925000 2015-09-25 00:47    71.625000 2015-09-25 00:48    71.333333 2015-09-25 00:49    64.571429 2015-09-25 00:50    72.285714 

but the index is of type string, but i need it a datetime format because i get the error

'Index' object has no attribute 'hour' 

when using

 df['A'] = df.index.hour 
like image 982
Runner Bean Avatar asked Nov 26 '16 05:11

Runner Bean


People also ask

How do I change the index of a DataFrame to a datetime?

To convert the index of a DataFrame to DatetimeIndex , use Pandas' to_datetime(~) method.

How do I change the index of a DataFrame in Pandas?

To reset the index in pandas, you simply need to chain the function . reset_index() with the dataframe object. On applying the . reset_index() function, the index gets shifted to the dataframe as a separate column.

How do you drop the index of a data frame?

The most straightforward way to drop a Pandas dataframe index is to use the Pandas . reset_index() method. By default, the method will only reset the index, forcing values from 0 - len(df)-1 as the index. The method will also simply insert the dataframe index into a column in the dataframe.

How do you reference a DataFrame index?

To get the index of a Pandas DataFrame, call DataFrame. index property. The DataFrame. index property returns an Index object representing the index of this DataFrame.


2 Answers

It should work as expected. Try to run the following example.

import pandas as pd import io  data = """value           "2015-09-25 00:46"    71.925000 "2015-09-25 00:47"    71.625000 "2015-09-25 00:48"    71.333333 "2015-09-25 00:49"    64.571429 "2015-09-25 00:50"    72.285714"""  df = pd.read_table(io.StringIO(data), delim_whitespace=True)  # Converting the index as date df.index = pd.to_datetime(df.index)  # Extracting hour & minute df['A'] = df.index.hour df['B'] = df.index.minute df  #                          value  A   B # 2015-09-25 00:46:00  71.925000  0  46 # 2015-09-25 00:47:00  71.625000  0  47 # 2015-09-25 00:48:00  71.333333  0  48 # 2015-09-25 00:49:00  64.571429  0  49 # 2015-09-25 00:50:00  72.285714  0  50 
like image 81
Romain Avatar answered Sep 30 '22 11:09

Romain


You could explicitly create a DatetimeIndex when initializing the dataframe. Assuming your data is in string format

data = [     ('2015-09-25 00:46', '71.925000'),     ('2015-09-25 00:47', '71.625000'),     ('2015-09-25 00:48', '71.333333'),     ('2015-09-25 00:49', '64.571429'),     ('2015-09-25 00:50', '72.285714'), ]  index, values = zip(*data)  frame = pd.DataFrame({     'values': values }, index=pd.DatetimeIndex(index))  print(frame.index.minute) 
like image 37
blue_note Avatar answered Sep 30 '22 13:09

blue_note