Roy
Roy

Reputation: 537

Set DateTimeIndex in existing DataFrame

I have a existing dataframe, df, which consists of the following structure:

   tick_id    stock_ticker        tick_datetime  price  volume
0   160939   A2M AU Equity  2016-10-19 09:00:00  450.0   79700
1   160940   A2M AU Equity  2016-10-19 09:00:01  450.0     100
2   160941   A2M AU Equity  2016-10-19 09:00:01  450.0    2500
3   160942   A2M AU Equity  2016-10-19 09:00:01  451.0     200

What I am looking to do is to set the "tick_datetime" as the index of the dataframe, so that it should become DateTimeIndex for easier data manipulation later.

However, executing the following command yields unexpected result.

df.set_index('tick_datetime')

What is the correct way to achieve my desired outcome?

Upvotes: 4

Views: 8171

Answers (1)

brunormoreira
brunormoreira

Reputation: 248

Try:

df['tick_datetime'] = pd.to_datetime(df['tick_datetime'])   
df.set_index('tick_datetime',inplace=True)

or:

df['tick_datetime'] = pd.to_datetime(df['tick_datetime'])
df = df.set_index('tick_datetime')

Upvotes: 10

Related Questions