Home > Software design >  Datetime format update for a range of columns in pandas
Datetime format update for a range of columns in pandas

Time:10-27

I have a pandas dataframe with a subset of 30 columns with values per month, named like "2018-09-01 00:00:00", which I want to reformat to a Month-Year like "Sep 2018".

I found this useful:

df.iloc[:, 13:].rename(columns='{:%b %Y}'.format)

but applying it to whole df ruins data in these columns:

df.iloc[:, 13:] = df.iloc[:, 13:].rename(columns='{:%b %Y}'.format)

How do I change format in a range of columns, that I know by index?

CodePudding user response:

Use rename:

old_col_names = df.filter(regex=r'\d{4}-\d{2}').columns.tolist()
new_col_names = pd.to_datetime(old_col_names).strftime('%b %Y')
df = df.rename(columns=dict(zip(old_col_names, new_col_names)))

Output:

# Before rename
>>> df
   id  2018-09-01 00:00:00  2018-10-01 00:00:00  data
0   0                    1                    2     3

# After rename
>>> df
   id  Sep 2018  Oct 2018  data
0   0         1         2     3

Setup:

data = {'id': [0], '2018-09-01 00:00:00': [1],
        '2018-10-01 00:00:00': [2], 'data': [3]}
df = pd.DataFrame(data)
  • Related