首页 > 解决方案 > 仅将月份从“jan”更改为 1,“feb”更改为 2,“mar”更改为 3...“dec”更改为 12

问题描述

我让它工作了一次,但没有保存文件并丢失了代码。请帮忙。

 import pandas as pd
 import nltk

 df0.head(4)

#   X   Y   month   day FFMC    DMC DC
# 0 7   5   mar fri 86.2    26.2    94.3
# 1 7   4   oct tue 90.6    35.4    669.1


 monthdict={'jan':1,'feb':2'mar':3,'oct':10,'nov':11,'dec':12}

 def month2num(month):
    return monthdict[month]
 df0['month'] = df0['month'].apply(month2num)
 df0.head()

'评论'我不是那么聪明,刚刚开始,所以请有人用英语解释解决方案。

下面的错误打印输出:

# KeyError                                  
# Traceback 
# (most recent call last)
# <ipython-input-48-566f3675aaed> in <module>()
#       def month2num(month):
#           return monthdict[month]
# ----> df0['month'] = df['month'].apply(month2num)
#       df0.head()

# 1 frames
# pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

# <ipython-input-48-566f3675aaed> in month2num(month)
#        
#        def month2num(month):
# ---->      return monthdict[month]
#        df0['month'] = df['month'].apply(month2num)
#        df0.head()

# KeyError: 'apr'

标签: pythonpandas

解决方案


字典的替代方法可以是在元组中使用索引(尽管使用字典进行散列可能更快):

months = (None, 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
integervalue = months.index(monthstring)

推荐阅读