Home > Software design >  How to replace values in pandas column only if the starting characters match?
How to replace values in pandas column only if the starting characters match?

Time:01-08

I have a column which has time values as string

a_time = [ "10:10 AM", "0:10 AM", "0:45 PM", "7:51 am"]
timedf = pd.DataFrame(a_time, columns = ['Time_col'])
timedf 

o/p

    Time_col
0   10:10 AM
1   0:10 AM
2   0:45 PM
3   7:51 am

I am trying to convert anything which starts with 0: into 12: if i use the replace string then it replaces first row into 112:10 AM which is not correct.

timedf['Time_col'] = timedf['Time_col'].str.replace('0:', '12:')
timedf

o/p

    Time_col
0   112:10 AM
1   12:10 AM
2   12:45 PM
3   7:51 am

How to i specify the condition to only consider the string starting with 0 only?

Thanks in advance

CodePudding user response:

You can add ^ for match start of string, regex=True is for avoid FutureWarning:

timedf['Time_col'] = timedf['Time_col'].str.replace('^0:', '12:', regex=True)
print (timedf)
   Time_col
0  10:10 AM
1  12:10 AM
2  12:45 PM
3   7:51 am

CodePudding user response:

This method also you can use and regex method is also good as shown in another answer.

timedf["Time_col"].loc[timedf['Time_col'].str.startswith('0')] = timedf["Time_col"].str.replace("0:","12:")

It will filter Time_col values where starting value is 0 and it replaces 0: with 12:

It's giving the following output

Time_col
10:10 AM
12:10 AM
12:45 PM
7:51 am
  •  Tags:  
  • Related