Home > Software engineering >  Convert all dates column to datetime of multiple DataFrames in a dictionary
Convert all dates column to datetime of multiple DataFrames in a dictionary

Time:12-15

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'])

Thanks a lot!

CodePudding user response:

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()}
  • Related