Python Forum
Problem with replacing strings
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with replacing strings
#1
Hi guys,

I got a data set with Dates looking like this :

Jan. 01
Feb. 01
Mar. 01

and so on. It seems Python can't transform this kind of date format using

df['Date'] = pd.to_datetime(df['Date'])
In order to work I guess the format has to be:

Jan. 2001
Feb. 2001
Mar. 2001

What I have been trying, and I am 100% sure there is a fancier way, is to replace all "01" with "2001" and so on. The code looks like that :

for i in range(len(df["Date"])):
        df["Date"][i] = df["Date"][i].replace("00","2000")
        df["Date"][i] = df["Date"][i].replace("01","2001")
        df["Date"][i] = df["Date"][i].replace("02","2002")
        df["Date"][i] = df["Date"][i].replace("03","2003")
The problem what that code is, that transformed strings, e.g. 2020, are getting replaced again, because they have the string "02" in them. As a result, I get dates like : Jan 202000 Blush
Is there a way to fix my approach, or a different approach that solves my problem?
Reply
#2
def y2k(datestr):
    year=datestr.split()[-1]
    if len(year) < 4:
        return datestr[:-2]+'20'+datestr[-2:]
    return datestr

print(y2k('Jan. 01'))
print(y2k('Jan. 1999'))
Reply
#3
Maybe something along these lines:

>>> import pandas as pd
>>> df = pd.DataFrame({'date': ['Jan. 01', 'Feb. 01', 'Mar. 01']})
>>> df
      date
0  Jan. 01
1  Feb. 01
2  Mar. 01
>>> df['date'] = pd.to_datetime(df['date'], format='%b. %y') 
>>> df
        date
0 2001-01-01
1 2001-02-01
2 2001-03-01
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
Both methods worked! Thank you so much
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand strings and lists of strings Konstantin23 2 757 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 691 Jul-19-2023, 06:46 PM
Last Post: deanhystad
  Splitting strings in list of strings jesse68 3 1,757 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Finding multiple strings between the two same strings Slither 1 2,511 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  lists, strings, and byte strings Skaperen 2 4,214 Mar-02-2018, 02:12 AM
Last Post: Skaperen
  [split] Problem with integers and strings aka2d7 3 3,463 Jan-05-2018, 02:26 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020