David
David

Reputation: 487

Converting timestamp into Month name and year as a Data frame column name

I am trying to convert the a Data frame column name (Timestamp) into the written abbreviation of that month and the year.

Here is an example of the current data frame:

             2016-01-01  2016-02-01  2016-03-01  2016-04-01 
               00:00:00    00:00:00     00:00:00    00:00:00
Metric 1         Data          Data        Data         Data
Metric 2         Data          Data        Data         Data
Metric 3         Data          Data        Data         Data

This is my desire output:

               Jan 2016    Feb 2016    March 2016   April 2016
 Metric 1         Data       Data          Data         Data
 Metric 2         Data       Data          Data         Data    
 Metric 3         Data       Data          Data         Data

Here is the code I used to build the Data Frame:

start = '2016-01-01'
end = '2016-04-01'
data_dates = pd.date_range(start, end, freq='MS')
data_results = pd.DataFrame(data_dates)
data_results.columns = ['Date']

data_results = data_results['Date'].tolist()
df = pd.DataFrame(columns = data_results,  index = ['Metric 1', 'Metric 2', 'Metric 3'])

I have try using the following with no results.

data_results['Date'] = data_results['Date'].apply(lambda x: calendar.month_abbr[x])

Upvotes: 1

Views: 1933

Answers (2)

piRSquared
piRSquared

Reputation: 294198

Assuming your column names are already timestamps.

df.rename(columns='{:%b %Y}'.format)

         Jan 2016 Feb 2016 Mar 2016 Apr 2016
Metric 1     Data     Data     Data     Data
Metric 2     Data     Data     Data     Data
Metric 3     Data     Data     Data     Data

Upvotes: 3

Vaishali
Vaishali

Reputation: 38415

Assuming the columns are not currently in datetime format,

df.columns = pd.to_datetime(df.columns).strftime('%b %Y')

            Jan 2016    Feb 2016    Mar 2016    Apr 2016
Metric 1    NaN         NaN         NaN         NaN
Metric 2    NaN         NaN         NaN         NaN
Metric 3    NaN         NaN         NaN         NaN

Edit: I missed the code used to generate the df, since they are already datetime,

df.columns = df.columns.strftime('%b %Y')

Upvotes: 3

Related Questions