2

I have this pandas dataframe including a column for months whose type is int64, and I want to change every value in the column to be the corresponding season of the year.

For example if x is any of 12, 1, or 2, change the value of x to 'winter', etc.

I have tried some for loops but no use. I think there is a one liner that can do this using lambda x.

I supposed that every month has only 1 season so for example winter is in months 12, 1, and 2, and so on.

For example (0, 1, and 2 are indices):

input:

0  1
1  3
2  6

output:

0  winter
1  spring
2  summer

My problem is with month 12 or else I could have used bins.

Any ideas?

1

4 Answers 4

1

One fast and flexible way is to map a dict from current column values to new column values:

d = dict(zip(range(1,13), ["winter"]*2 + ["spring"]*3 + ["summer"]*3 + ["fall"]*3 + ["winter"]))    
df = pd.DataFrame(dict(month=[3,4,6,1,5,6,2,4,5]))

df = df.month.map(d)

output:

0    spring
1    spring
2    summer
3    winter
4    spring
5    summer
6    winter
7    spring
8    spring
Name: month, dtype: object
Sign up to request clarification or add additional context in comments.

1 Comment

Ok thank you for this nice solution
1

map accepts a dict or a Series. (Values that are not found in the dict are converted to NaN.)

month2season = {1:'winter', 2:'winter', 3:'spring', ...}
s.map(month2season)  # s.apply(month2season) does the same thing

1 Comment

that;'s very helpful actually thanks
0

suppose you have this dataframe (named df)

enter image description here

then u can easily write this function

def map_fn(x: int):
    if x in range(3, 6):
        return "spring"
    if x in range(6, 9):
        return "summer"
    if x in range(9, 12):
        return "autumn"
    return "winter"

and then apply it to your column like this

df.seasons.apply(map_fn) 

to have this

enter image description here

3 Comments

Please don't post pictures of text. Instead, copy the text, edit it into your post, and use the formatting tools like code formatting.
Not a big deal, but the second two ifs should be elifs.
NaNs will be mapped to 'winter', which is probably not what you want. You could add another check: elif x in range(1, 3) or x == 12: return "winter", although NaNs will be mapped to None. hmm... I'm not sure how to fix that.
0

I solved it using pandas replace and cut methods:

df['month']=df['month'].replace(12,0)

bin_edges = [-1,2,5,8,11]

bin_labels= ["winter",'spring','summer','fall']

df['month']=pd.cut(df['month'], bin_edges, labels=bin_labels)

Thanks all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.