Home > Software engineering >  reverse a string column in pandas dataframe in a speicifc order
reverse a string column in pandas dataframe in a speicifc order

Time:01-18

I have this column in my dataframe, which is basically a date.

0       2023-01-01
1       2023-01-01
2       2023-01-01
3       2023-01-01
4       2023-01-01
           ...    
1015    2023-01-17
1016    2023-01-17
1017    2023-01-17
1018    2023-01-17
1019    2023-01-17

I want to convert the above column into

0       01-01-2023
1       01-01-2023
2       01-01-2023
3       01-01-2023
4       01-01-2023
           ...    
1015    17-01-2023
1016    17-01-2023
1017    17-01-2023
1018    17-01-2023
1019    17-01-2023

I tried to use this:

df['date'] = "-".join(reversed(df['date'].split("-")))

But I'm getting below error:

AttributeError: 'Series' object has no attribute 'split'

Is there a better way to change this column?

CodePudding user response:

Use lambda function:

df['date'] = df['date'].apply(lambda x: "-".join(reversed(x.split("-"))))
df['date'] = df['date'].str.split('-').apply(reversed).str.join('-')

Better solution is convert datetimes to custom strings:

df['date'] = pd.to_datetime(df['date']).dt.strftime('%d-%m-%Y')

CodePudding user response:

We could use str.replace here for a regex option:

df["date"] = df["date"].str.replace(r'(\d{4})-(\d{2})-(\d{2})', r'\3-\2-\1', regex=True)

However, the "better" solution as given by @jezrael is to convert your text date column to a bona-fide date. Then, if you want to view your dates in a certain format, use strptime().

  • Related