How can I change values in the column contating Nan and certain values of Dataframe in Python?

I have a problem about changing certain values (Non-Nan Values) in a MONTH column of the dataframe. The month column contains the deduction month name of a year except for NaN values. I try to redefine the full name of each one in a MONTH column but I couldn't do that.

Here is my code showing unique values of the Month column

df[df["MONTH"].notnull()]["MONTH"].unique()

array(['Aug', 'Mar', 'Oct', 'Nov', 'May', 'Sep', 'Apr', 'Jul', 'Jun',
       'Jan', 'Feb', 'Dec'], dtype=object)

Here is my code which is shown below.

df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Aug', 'MONTH'] = "August"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Mar', 'MONTH'] = "March"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Oct', 'MONTH'] = "October"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Nov', 'MONTH'] = "November"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'May', 'MONTH'] = "May"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Sep', 'MONTH'] = "September"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Apr', 'MONTH'] = "April"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Jul', 'MONTH'] = "July"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Jun', 'MONTH'] = "June"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Jan', 'MONTH'] = "January"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Feb', 'MONTH'] = "February"
df.loc[df[df["MONTH"].notnull()]["MONTH"] == 'Dec', 'MONTH'] = "December"

Here is the error which is shown below.

TypeError: 'Series' objects are mutable, thus they cannot be hashed

How can I fix it?

Upvotes: 0

Views: 35

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18367

Please let me suggest a perhaps better way of dealing with the issue (the possible problem in your code is addressed below). Simply use pandas replace() in a single line. It will be a lot more efficient, as your code is calling and slicing the dataframe object 12 times instead of once.:

replacements = {'Jan':'January','Feb':'Febraury','Mar':'March','Apr':'April','May':'May','Jun':'June','Jul':'July','Aug':'August','Sep':'September','Oct':'October','Nov':'Novemeber','Dec':'December'}

df['MONTH'] = df['MONTH'].replace(replacements)

With regards to your error, I think you can add .index in order to help you get the first argument of loc:

df.loc[(df[df["MONTH"].notnull()]["MONTH"] == 'Aug').index, 'MONTH'] = "August"

Upvotes: 1

Related Questions