For some reason I cannot convert columns of different dataframes:
JavaScript
x
6
1
cols_to_change = [df1['date1'], df2['date2'], df3['date3']]
2
3
for i in cols_to_change:
4
i = pd.to_datetime(i, format = '%Y-%m-%d')
5
6
although str can be converted to datetime.
But it works ok if I write
JavaScript
1
3
1
df1['date1'] = pd.to_datetime(df1['date1'], format = '%Y-%m-%d')
2
df2['date2'] = pd.to_datetime(df2['date2'], format = '%Y-%m-%d')
3
And if I call
JavaScript
1
2
1
pd.to_datetime(df1['date1'].loc[0], format = '%Y-%m-%d')
2
it returns a Timestamp. Is this the point?
Advertisement
Answer
pd.to_datetime
returns a new Series and you assigned that series to i
, which you never used after the conversion.
You need to refer to the original dataframe and column:
JavaScript
1
9
1
cols_to_change = [
2
(df1, 'date1'),
3
(df2, 'date2'),
4
(df3, 'date3')
5
]
6
7
for df, col in cols_to_change:
8
df[col] = pd.to_datetime(df[col], format='%Y-%m-%d')
9