0

I converted a column to index and now I tried to convert it into a date time index. But got the error.

My code:

df.set_index('Time',inplace=True) % This worked perfectly

df.index = 
ndex(['5/7/2020 7:01', '5/7/2020 7:02', '5/7/2020 7:03', '5/7/2020 7:04',
       '5/7/2020 7:05', '5/7/2020 7:06', '5/7/2020 7:07', '5/7/2020 7:08',
       '5/7/2020 7:09', '5/7/2020 7:10',
       ...
       ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
      dtype='object', name='Time', length=1441)
df.index = pd.to_datetime(df.index)

Present output:

ValueError: ('String does not contain a date:', ' ')

enter image description here

Msquare
  • 775
  • 7
  • 17
  • It seems you have many `' '` values in the index, how do you deal with those? – Celius Stingher Jun 30 '20 at 19:08
  • Tried to convert column 'Time' to datetime first? Maybe you need to specify a format - or set errors = 'coerce' – FObersteiner Jun 30 '20 at 19:09
  • @CeliusStingher I placed a screen shot. I agree with you that i have `' ''. In the dataframe, I see empty rows with only index. Looks like they are causing error. How to omit them – Msquare Jun 30 '20 at 19:12
  • Maybe you need this: https://stackoverflow.com/questions/29314033/drop-rows-containing-empty-cells-from-a-pandas-dataframe – FObersteiner Jun 30 '20 at 19:20

1 Answers1

0

If you want to omit the values that can't be turned into DateTime objects, you can use the argument errors='coerce' in your function, this will return NaT for the values which would have raised an error. Furthermore you should add the format or, use infer_datetime_format=True, this might also save some issues. All in all, you should try:

df.index = pd.to_datetime(df.index,infer_datetime_format=True,errors='coerce')
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53