'Python Pandas - Date Column to Column index

I have a table of data imported from a CSV file into a DataFrame.

The data contains around 10 categorical fields, 1 month column (in date time format) and the rest are data series.

How do I convert the date column into an index across the the column axis?



Solution 1:[1]

You can use set_index:

df.set_index('month')

For example:

In [1]: df = pd.DataFrame([[1, datetime(2011,1,1)], [2, datetime(2011,1,2)]], columns=['a', 'b'])

In [2]: df
Out[2]: 
   a                   b
0  1 2011-01-01 00:00:00
1  2 2011-01-02 00:00:00

In [3]: df.set_index('b')
Out[3]: 
            a
b            
2011-01-01  1
2011-01-02  2

Solution 2:[2]

I had similar problem I've just solved by reset_index. But you can use either set_index or reset_index:

df_ind = df.set_index(['A', 'B'])

Or

df.reset_index(level=0, inplace=True)

Solution 3:[3]

If you don't know the name of the date column ahead of time and need to set the index automatically based on the time series column in the data

df.set_index((df.select_dtypes(include=[np.datetime64]).columns).tolist())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy Hayden
Solution 2
Solution 3 Shankar ARUL