vsoler
vsoler

Reputation: 1173

Converting object to date type in index

I have read some data in the clipboard using

clipdf = pd.read_clipboard()

            A           B           C           D   F
2013-01-01  0.000000    0.000000    -1.509059   5   NaN
2013-01-02  1.212112    -0.173215   0.119209    5   1.0
2013-01-03  -0.861849   -2.104569   -0.494929   5   2.0
2013-01-04  0.721555    -0.706771   -1.039575   5   3.0
2013-01-05  -0.424972   0.567020    0.276232    5   4.0
2013-01-06  -0.673690   0.113648    -1.478427   5   5.0

But I realize that the index is of type object

Index(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05',
       '2013-01-06'],
      dtype='object')

...instead of type datetime64

DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')
  1. Is it important that I convert the index to a Datetime64 type?
  2. How can I do it in practice?

Regards

Upvotes: 1

Views: 59

Answers (1)

jezrael
jezrael

Reputation: 862761

I think you need parameter parse_dates=True for DatetimeIndex:

clipdf = pd.read_clipboard(parse_dates=True)
print (clipdf.index)

DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq=None)

Or:

clipdf = pd.read_clipboard()
clipdf.index = pd.to_datetime(clipdf.index)
#alternative
#clipdf.index = pd.DatetimeIndex(clipdf.index)
print(clipdf.index)
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq=None)

Is it important that I convert the index to a Datetime64 type?

I think it depends what you need. But obviously yes, especialy if working with function like resample. Also performance should be better.

Upvotes: 1

Related Questions