简体   繁体   中英

Combine month name and year in a column pandas python

df

Year   Month Name    Avg
2015    Jan           12
2015    Feb           13.4
2015    Mar           10     
...................
2019   Jan           11
2019   Feb           11

Code

df['Month Name-Year']= pd.to_datetime(df['Month Name'].astype(str)+df['Year'].astype(str),format='%b%Y')

In the dataframe, df, the groupby output avg is on keys month name and year. So month name and year are actually multilevel indices. I want to create a third column Month Name Year so that I can do some operation (create plots etc) using the data.

The output I am getting using the code is as below:

   Year   Month Name    Avg        Month Name-Year
   2015    Jan           12       2015-01-01
   2015    Feb           13.4     2015-02-01
   2015    Mar           10       2015-03-01
    ...................
    2019   Nov           11       2019-11-01
    2019   Dec           11       2019-12-01

and so on.

The output I want is 2015-Jan, 2015-Feb etc in Month Name-Year column...or I want 2015-01, 2015-02...2019-11, 2019-12 etc (only year and month, no days).

Please help

One type of solution is converting to datetimes and then change format by Series.dt.to_period or Series.dt.strftime :

df['Month Name-Year']=pd.to_datetime(df['Month Name']+df['Year'].astype(str),format='%b%Y')

#for months periods
df['Month Name-Year1'] = df['Month Name-Year'].dt.to_period('m')
#for 2010-02 format
df['Month Name-Year2'] = df['Month Name-Year'].dt.strftime('%Y-%m')

Simpliest is solution without convert to datetimes only join with - and convert years to strings:

#format 2010-Feb
df['Month Name-Year3'] = df['Year'].astype(str) + '-' + df['Month Name']

...what is same like converting to datetimes and then converting to custom strings:

#format 2010-Feb
df['Month Name-Year31'] = df['Month Name-Year'].dt.strftime('%Y-%b')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM