[英]How to replace values in pandas column only if the starting characters match?
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 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.我正在尝试将以 0: 开头的任何内容转换为 12: 如果我使用替换字符串,那么它将第一行替换为 112:10 AM,这是不正确的。
timedf['Time_col'] = timedf['Time_col'].str.replace('0:', '12:')
timedf
o/p 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?如何指定条件以仅考虑仅以 0 开头的字符串?
Thanks in advance提前致谢
You can add ^
for match start of string, regex=True
is for avoid FutureWarning
:您可以添加
^
作为字符串的匹配开始, regex=True
是为了避免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
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:它将过滤起始值为 0 的 Time_col 值,并将 0: 替换为 12:
It's giving the following output它给出了以下 output
Time_col ![]() |
---|
10:10 AM![]() |
12:10 AM![]() |
12:45 PM![]() |
7:51 am![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.