Question: I am trying to change the format of the date in a pandas dataframe. 
If I check the date in the beginning, I have:

```
df['Date'][0]
Out[158]: '01/02/2008'

```

Then, I use:

```
df['Date'] = pd.to_datetime(df['Date']).dt.date  

```

To change the format to 

```
df['Date'][0]
Out[157]: datetime.date(2008, 1, 2)

```

However, this takes a veeeery long time, since my dataframe has millions of rows. 

All I want to do is change the date format from MM-DD-YYYY to YYYY-MM-DD.
How can I do it in a faster way?

Answer: 
You should first collapse by `Date` using the `groupby` method to reduce the dimensionality of the problem.

Then you parse the dates into the new format and merge the results back into the original DataFrame.

This requires some time because of the merging, but it takes advantage from the fact that many dates are repeated a large number of times. You want to convert each date only once!

You can use the following code:

```
date_parser = lambda x: pd.datetime.strptime(str(x), '%m/%d/%Y')

df['date_index'] = df['Date']
dates = df.groupby(['date_index']).first()['Date'].apply(date_parser)

df = df.set_index([ 'date_index' ])
df['New Date'] = dates
df = df.reset_index()

df.head()

```

In my case, the execution time for a DataFrame with 3 million lines reduced from 30 seconds to about 1.5 seconds.
I'm not sure if this will help with the performance issue, as I haven't tested with a dataset of your size, but at least in theory, this should help. Pandas has a built in parameter you can use to specify that it should load a column as a date or datetime field. See the [parse\_dates](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) parameter in the pandas documentation.

Simply pass in a list of columns that you want to be parsed as a date and pandas will convert the columns for you when creating the DataFrame. Then, you won't have to worry about looping back through the dataframe and attempting the conversion after.

```
import pandas as pd

df = pd.read_csv('test.csv', parse_dates=[0,2])

```

The above example would try to parse the 1st and 3rd (zero-based) columns as dates.

The type of each resulting column value will be a pandas timestamp and you can then use pandas to print this out however you'd like when working with the dataframe.