-1

I want to convert each value in a pandas dataframe column to a string and then delete some text. The values are times. For example, if the value is 11:21, I would like to delete every to the right of the : in every element in the column. 11:21 should be converted to 11.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
ILikePython
  • 17
  • 1
  • 5

1 Answers1

1

Let's say you have following dataset:

df = pd.DataFrame({
    'time': ['09:30:00','09:40:01','09:50:02','10:00:03']
})

df.head()

Output:

Output

If you want to work with time column as a string, following code may be used:

df['hour'] = df['time'].apply(lambda time : time.split(':')[0])

df.head()

Output:

Output

Alternatively time can be converted to datetime and hour can be extracted:

df['hour'] = pd.to_datetime(df['time'], format='%H:%M:%S').dt.hour

df.head()

Output:

Output

Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27