dimanche 3 octobre 2021

Question on how to add strings using Python if conditional statements

I have a question.
I'd appreciate it if you could help me.
I want to add a specific character in the middle of a string using a python ‘if’ statement.
For example,
When I change January 1, 2021 to a string, I want to convert 2020011 (7 letters) to 20200101 (8 letters).
This is my code I have tried

df2['date']=df2['date'].astype(str)
x = df2['date'].str.len()
def date_changing(x) :
    if x == 7: return df2.date.astype(str).apply(lambda z: z[:6] + '0' + z[6:])
    else: return df2.date.astype(str)

df2['new_date']=df2['date'].apply(date_changing)

There are other dates, so I'm trying to convert using an ‘if’ conditional to make things a little easier, but I get the following error.

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire