I have a dataset that has column names in datetime format:
And I would like to change their names to 2014-01-01 00:00:00 > Jan-14 and so on.
operations.columns = pd.to_datetime(operations.columns).to_period('M')
The above code gave me the following error:
ParserError: Unknown string format: Aircraft Name How should I approach this problem?
CodePudding user response:
here is one way to change it. Check if the column type is datetime, then reformat it otherwise, keep it as is
import datetime
operations.columns = [col.strftime('%M %d')
if (isinstance(col, datetime.date) )
else col
for col in operations.columns]
CodePudding user response:
you can parse the column names to datetime (and format to the desired format), then use only those elements where the conversion succeeds (else use the old elements). EX:
import pandas as pd
df = pd.DataFrame({'a': [1, 1, 1], 'b': [2, 2, 2], '2021-02-22 00:00:00': [3, 3, 3]})
newnames = pd.to_datetime(df.columns, errors='coerce').strftime("%b-%d")
df.columns = newnames.where(~newnames.isnull(), df.columns)
df
a b Feb-22
0 1 2 3
1 1 2 3
2 1 2 3