Ask Your Question
2

How can I use np.where in a pandas dataframe to change the date format from %d-%m-%y to %y-%m-%d in reverse order?

asked 2021-11-14 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-16 09:00:00 +0000

lalupa gravatar image

You can use np.where in combination with pandas' to_datetime function to achieve this. Here's an example:

import pandas as pd
import numpy as np

# create a sample dataframe
df = pd.DataFrame({'date': ['31-12-21', '01-01-22', '02-01-22']})

# use np.where to check if the date format is %d-%m-%y, and if so, convert it to %y-%m-%d
df['date'] = np.where(df['date'].str.match('\d{2}-\d{2}-\d{2}'),
                      pd.to_datetime(df['date'], format='%d-%m-%y').dt.strftime('%y-%m-%d'),
                      df['date'])

print(df)

Output:

        date
0  21-12-31
1  22-01-01
2  22-01-02

In the above code, str.match is used to check if the date format matches %d-%m-%y. If it does, pd.to_datetime is used to convert it to a datetime object and then dt.strftime is used to convert it to the desired format %y-%m-%d. If the date format does not match %d-%m-%y, the original value is kept unchanged.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-14 11:00:00 +0000

Seen: 7 times

Last updated: Mar 16 '22