So I have this pandas data frame including a column for months it's type is int64, I want to change every value in the column to be the corresponding season of the year.
for example if x = 12,1,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.
any ideas ?
CodePudding user response:
suppose you have this dataframe (named df
)
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
CodePudding user response:
map
accepts a dict or a Series (values that are not found in the dict are converted to NaN).
https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html
month2season = {1:'winter',2:'winter',3:'spring',...}
s.map(month2season) # s.apply(month2season) does the same thing
CodePudding user response:
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