Flying pig
Flying pig

Reputation: 612

How to join columns of year and month in Pandas?

I have a dataset look like this:

    Year    Month    Partisan Conflict
0   1981    January  68.944808
1   1981    February 64.907109
2   1981    March    79.058476
3   1981    April    69.324041
4   1981    May      88.194466

The data was imported from an excel file.

I am wondering how I can join the columns of year and month with a format like:

1981-01
1981-02
...

I checked the format of them.

type(df.iloc[0]['Month'])
str

type(df.iloc[0]['Year'])
numpy.int64

But to add them together is the question I haven't figure out. Can anyone help me? Thanks!

Upvotes: 2

Views: 788

Answers (2)

Madhuri Patel
Madhuri Patel

Reputation: 1270

Can you please try with below code?


Dates = {'Month': ['Jun','Jul','Aug','Sep','Oct'], 
        'Year': [2016,2017,2018,2019,2020]} 

df = DataFrame(Dates, columns= ['Month','Year']) 
df1 =  df['Month'].map(str) + '-' + df['Year'].map(str)

print (df1)




Note I just gave an example to resolve the issue.

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

First concatenate the Year and Month column then use, pd.to_datetime to transform this concatenated column to pandas datetime series then use Series.dt.strftime to convert this datetime series in required format:

df['Date'] = pd.to_datetime(
    df['Year'].astype(str) + df['Month'], format='%Y%B').dt.strftime('%Y-%m')

OR, it is also possible to use mappings dictionary to map the Month column using Series.map:

mappings = {'January': '01', 'February': '02', 'March': '03', 'April': '04', 'May': '05', 'June': '06',
            'July': '07',  'August': '08', 'September': '09', 'Octomber': '10', 'November': '11', 'December': '12'}

df['Date'] = df['Year'].astype(str) + '-' + df['Month'].map(mappings)

# print(df)
   Year     Month  Partisan Conflict     Date
0  1981   January          68.944808  1981-01
1  1981  February          64.907109  1981-02
2  1981     March          79.058476  1981-03
3  1981     April          69.324041  1981-04
4  1981       May          88.194466  1981-05

Upvotes: 3

Related Questions