1

I am slicing my hour column and when I use slice(1, 3) and slice(0, 3) I get the same results. What am i missing? See in the image below.

Original Column

slice(0, 3)

slice(1, 3)

David
  • 8,113
  • 2
  • 17
  • 36
Meet Shah
  • 73
  • 1
  • 8
  • 6
    Please, no photos of code, just code. – DavidO Oct 13 '20 at 04:47
  • Post a working example we can copy - including initializing the dataframe. Its best if its a small demonstration dataset. We don't need a dozen columns and who knows how many rows when the question regards a few columns. – tdelaney Oct 13 '20 at 04:51
  • It would be helpful if you can provide data for [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – akane Oct 13 '20 at 04:52
  • And include `dataset.dtypes`. If `02:00:00` is a string and you slice it to 0:3, you get `"02:"` which would fail when initializing an `int`. `dataset["hour"].str.sllice(0,3)` would be interesting to see what happens there. – tdelaney Oct 13 '20 at 05:07
  • 2
    My guess is there's a space at the beginning of `dataset["hour"]`. So `slice(0, 3)` is `" 02"` while `slice(1, 3)` is `"02"` – Barmar Oct 13 '20 at 05:24
  • @Barmar Thank you. And yes, you are right. There is indeed a space at the beginning. So, I didn't notice it. Also, can you guide me how to mark this as an answer because it is in a comment section and not answer section Sorry I'm new to stack overflow. – Meet Shah Oct 14 '20 at 03:13

2 Answers2

1

If it's needed to extract an hour from the time, it probably would be better to use:

dataset['hour'] = pd.to_datetime(dataset['hour'],format= '%H:%M:%S' ).dt.hour
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27
1

There is a space at the beginning of dataset["hour"].

So slice(0, 3) is " 02" while slice(1, 3) is "02".

This was answered by @Barmar on comment.

4b0
  • 21,981
  • 30
  • 95
  • 142
Meet Shah
  • 73
  • 1
  • 8