Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert all dates column to datetime of multiple DataFrames in a dictionary

I have multiple DataFrames stored in a dictionary and I try to change the type of the Dates column from object to datetime for all DataFrames in the dictionary at the same time.

This would be an example with two DataFrames df1 & df2.

import pandas as pd
df1 = pd.DataFrame({
    'Dates':['2021-01-01', '2021-01-03', '2021-01-04', '2021-01-05', '2021-01-06'],
    'ID1':[0,0,0.1,0.2,0.1],
    'ID2':[0,0,0.1,0.2,0.1],
    'ID3':[0.1,0,0,0.2,0.4],
    'ID4':[0,0,0.1,0.2,0.1], 
    'ID6':[0,0,0.1,0.2,0.1]})

df2 = pd.DataFrame({
    'Dates':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05'], 
    'ID2':[3,6,3,-1,3],
    'ID4':[1,2.4,-2,1,4],
    'ID5':[4,3,3,-3,4],
    'ID6':[2,1.5,2,-2,3]})

dfs = dict()
dfs['df1'] = df1
dfs['df2'] = df2

I try to figure out a way to convert the column; Dates to datetime format within the dictionary for all DataFrames at the same time. So far, I was only able to convert them individually before putting them together into a dictionary with: df1['Dates'] = pd.to_datetime(df1['Dates'])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks a lot!

>Solution :

Use dictionary comprehension with DataFrame.assign:

dfs = {k:v.assign(Dates = pd.to_datetime(v['Dates'])) for k, v in dfs.items()}

EDIT:

dfs = {k:v.assign(Dates = pd.to_datetime(v['Dates'])).sort_values('Dates', ignore_index=True) 
      for k, v in dfs.items()}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading