Home > Software engineering >  Question on how to add strings using Python if conditional statements
Question on how to add strings using Python if conditional statements

Time:10-04

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.

CodePudding user response:

Check function from module datetime - isoformat or more general strftime function. These function will convert it to the expected format for you.

CodePudding user response:

Apply function iterates row by row. Do not use the lambda function inside your function date_changing.

df2['date']=df2['date'].astype(str)

def date_changing(x) :
    if len(x) == 7: return x[:6]   '0'   x[6:]
    else: return x

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

#Another Solution would be to use pandas.to_datetime

df2['date']=df2['date'].astype(str)
df2['new_date'] = pd.to_datetime(df2['date'], format = '%Y%m%d').dt.strftime('%Y%m%d')

CodePudding user response:

Code to create the df:

import pandas as pd
from io import StringIO
d = '''
Date
2020011 
20200101
'''
df = pd.read_csv(StringIO(d))
df

Output:

    Date
0   2020011
1   20200101

Code to apply insert '0' into string:

df.applymap(lambda x: str(x) if len(str(x)) == 8 else str(x)[:6]   '0'   str(x)[6:])

Output:

Date
0   20200101
1   20200101
  • Related