0

This question is related to the following one here Hours and time converting

I have got the following array with the corresponding values form the previous question:

a = [[7.15, 7.45, 9.30, 10.45, 13.45, 15.15, 15.45, 21.30]]

its values are floats and they represent hours of a day, e.g. 7.15 is equal to 7:15. Now I am using the following formula to in pandas to make a comaprison:

df.loc[([df['orders_time'] >= a[0]) & (df['orders_time'] <= a[1]), 'new_time'] = 10

It returns an error saying:

Invalid comparison between dtype=datetime64[ns] and float64

I tried to change the format of the values in a I was not able to run it.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Dave Will
  • 95
  • 7
  • The question stated that 7.25 would represent 7.15. I read it. – Wolf Feb 10 '21 at 15:52
  • 1
    Than the statement " its values are floats and they represent hours" must be corrected. It's a special format that deserves much more explanation. What about `7.88`? What about `7.155`? – Wolf Feb 10 '21 at 15:55
  • I gave these numbers as to show you that your float values ***don't represent hours*** -- to me it seems obvious that they are not even float.For comparing it with datetime values you ***have to convert*** them into normal floats (e.g. `"7.15"` -> `7.25`), else you will cause very ugly errors at runtime just *because* it doesn't crash. – Wolf Feb 10 '21 at 16:07
  • 2
    I think you can just convert the floats to datetime with the correct format string. Something like `pd.to_datetime(df['orders_time], format = '%H.%S').time()` – dubbbdan Feb 10 '21 at 16:09
  • Your code snippets contradict each other: first you tell us that `a` is a `list` with a `list` in it, next you tell us that you get a float from `a[0]`. Please fix it! Thanks. – Wolf Feb 10 '21 at 16:15

1 Answers1

1

You can convert a into a list of times.

a = [pd.to_datetime(i, format = '%H.%M').time() for i in a[0]]

then you can compare time to time using:

df.loc[([df['orders_time'].dt.time >= a[0]) & (df['orders_time'].dt.time <= a[1]), 'new_time'] = 10 
dubbbdan
  • 2,650
  • 1
  • 25
  • 43
  • 2
    format='%H.%M' I think - but if you have a look at the OP's other question, this is not necessary in the first place. – FObersteiner Feb 10 '21 at 17:04
  • 2
    Maybe it's time to remove/replace above comment now? – Wolf Feb 10 '21 at 17:19
  • @Wolf Thank you very much for your comments. I tried to remove the ban, but it is valid. Could you please help me or give me some tipps to remove it? Thank you! – Dave Will Feb 24 '21 at 09:43
  • @DaveWill sorry, I don't understand what you are referring to, what do you mean by ban? – Wolf Feb 24 '21 at 15:38