Reputation: 197
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
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
Reputation: 323266
Try
df.year*100 + df.Month
Out[415]:
0 202005
1 202006
2 202011
dtype: int64
Upvotes: 5
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