astroboy
astroboy

Reputation: 197

How to merge month and year columns in Pandas to yyyymm format?

Hello Stack overflow community!

Month     year    
  5       2020
  6       2020
 11       2020

How to merge these two columns into yearmonth (yyyymm) format in Pandas

yearmonth
  202005
  202006
  202011

Thank you in advance

Upvotes: 0

Views: 226

Answers (3)

Soumendra Mishra
Soumendra Mishra

Reputation: 3653

You can try this option:

df = pd.read_csv('file.csv', converters={'month': '{:0>2}'.format}).astype('str')
df['yearmonth'] = df['year'] + df['month']
print(df)

Upvotes: 0

BENY
BENY

Reputation: 323266

Try

df.year*100 + df.Month
Out[415]: 
0    202005
1    202006
2    202011
dtype: int64

Upvotes: 5

Quang Hoang
Quang Hoang

Reputation: 150745

We can convert them into strings and use zfill:

yearmonth = df.year.astype(str) + df.Month.astype(str).str.zfill(2)

Output:

0    202005
1    202006
2    202011
dtype: object

Upvotes: 2

Related Questions