I have this dataframe (dd) like this
|Month||Price|
1 55.96
6 381.16
7 825.80
I want to replace the value of the month in each row with the related month. I created a dictionary
R={'January': 1,'June': 6,'July': 7,'August': 8,'September': 9,'October': 10,'November': 11,'December': 12}
and then I used this in an attempt to do the replacements
dd['Month']=dd["Month"].map(R)
but when I print out my data frame I get this as an output:
Month Price
NaN 55.96
NaN 381.16
NaN 825.80
I'm not sure why I am getting NaN. Clearly something is happening but I have no idea what, why, and how to fix it.
I am new to python so still figuring out my way. My formatting in this q is probably a dead giveaway lol. Please dumb down your explanations :)
CodePudding user response:
Your mapping dictionary is set up the wrong way. You need to reverse key-value pairs:
reverse_R = {v:k for k,v in R.items()}
df['Month'] = df['Month'].map(reverse_R)
Output:
Month Price
0 January 55.96
1 June 381.16
2 July 825.80
CodePudding user response:
Try flipping your dictionary around so that the key is the integer and the value contains the month as a string.
R = {1:'January', 6:'June', 7:'July', 8:'August', 9:'September', 10: 'October', 11: 'November', 12:'December'
The map method maps keys to values. Your dictionary was just reversed.
Furthermore, according to the documentation if a value is missing the map function will return a NaN.
CodePudding user response:
Because your month dictionary key and values are vice versa , it should be like this :
R={1:'January',6:'June',7:'July'}
then it works :
dd['Month']=dd["Month"].map(R)
output>
month Price
0 January 55.96
1 June 381.16
2 July 825.80
