我正在尝试将一些值从字典映射到数据框。数据框中有一个标题为month的列,其值从1到12。我的字典将数字月份值等同于其名称,例如1月1日...
当我尝试下面的代码时,我会得到NaN并且不确定原因。
month_dict = {"1" : "January", "2" : "February", "3" : "March", "4" : "April", "5" : "May" , "6" : "June", "7" : "July", "8" : "August", "9" : "September", "10" : "October" ,"11" : "November","12" : "December"}
df['month'] = df['month'].map(month_dict)
我希望用月份名称代替等价的数字,但只返回NaN。有人可以帮忙吗?
答案 0 :(得分:1)
列和字典键中需要相同类型的数据。
匹配字符串的解决方案:
将列转换为字符串,因为字典中键中的字符串:
month_dict = {"1" : "January", "2" : "February", "3" : "March", "4" : "April",
"5" : "May" , "6" : "June", "7" : "July", "8" : "August",
"9" : "September", "10" : "October" ,"11" : "November","12" : "December"}
df['month'] = df['month'].astype(str).map(month_dict)
匹配整数的解决方案:
将字典中的键转换为整数:
month_dict = {int(k):v for k, v in month_dict.items()}
print (month_dict)
{1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June',
7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}
df['month'] = df['month'].map(month_dict)