I've a df
Like this
time_col
0 02:10:41
1 09:19:22
2 10:55:46
3 30:64:50
I want to remove both trailing
and 'Leading` zeros.
My expected output should look like
time_col Time
0 02:10:41 2:10:41
1 09:19:22 9:19:22
2 10:55:46 10:55:46
3 30:64:50 30:64:5
Any suggestions would be appriciated
CodePudding user response:
Use str.strip
:
df['time_col'] = df['time_col'].str.strip('0')
NB. There are also str.lstrip
and str.rstrip
to limit to left/right stripping respectively.
Output:
time_col
0 2:10:41
1 9:19:22
2 10:55:46
3 30:64:5
CodePudding user response:
If you want to remove Leading zeros
use lstrip()
df['Time'] = df['time_col'].astype('str').apply(lambda x: x.lstrip('0'))
#output
time_col Time
0 02:10:41 2:10:41
1 09:19:22 9:19:22
2 10:55:46 10:55:46
3 30:64:50 30:64:50
If you want to remove Trailing zeros
use rstrip()
df['Time'] = df['time_col'].astype('str').apply(lambda x: x.rstrip('0'))
#output
0 02:10:41 02:10:41
1 09:19:22 09:19:22
2 10:55:46 10:55:46
3 30:64:50 30:64:5
Your case...If you want to remove both Leading
and trailing
use strip()
df['Time'] = df['time_col'].astype('str').apply(lambda x: x.strip('0'))
#output
time_col Time
0 02:10:41 2:10:41
1 09:19:22 9:19:22
2 10:55:46 10:55:46
3 30:64:50 30:64:5