Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change season in pandas

I have a dataset like this

Month Season
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3
9 4
10 4
11 4
12 1

Now I would like to change 1 to winter, 2 to spring, 3 to summer and 4 to autumn in the season column.

I was struggling.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want this dataset after

Month Season
1 winter
2 winter
3 spring
4 spring
5 spring
6 summer
7 summer
8 summer
9 autumn
10 autumn
11 autumn
12 winter

I gave the following code

df.replace({'Season' : { 1 : winter, 2 : spring, 3: summer, 4: autumn}})

But got an error

The error is could not find winter???

>Solution :

# create a dictionary for season
d={1:'winter', 2 : 'spring', 3 : 'summer', 4 : 'autumn'}

# map season value using dictionary
df['Season']=df['Season'].map(d)
df
Month   Season
0   1   winter
1   2   winter
2   3   spring
3   4   spring
4   5   spring
5   6   summer
6   7   summer
7   8   summer
8   9   autumn
9   10  autumn
10  11  autumn
11  12  winter

Alternately, for completeness sake. you can update your solution of using replace as follows (as others have commented here), which results in the same result


df.replace({'Season' : { 1 : 'winter', 2 : 'spring', 3: 'summer', 4: 'autumn'}})

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading