【发布时间】:2019-06-10 07:15:21
【问题描述】:
我让它工作了一次,但没有保存文件并丢失了代码。 请帮忙。
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'
【问题讨论】:
-
错误提示您的字典
monthdict没有apr键。 -
你可以只做
pd.to_datetime(df.month,format='%b').dt.month而不是函数 -
您的月份字典中没有 april,您的代码很好(尽管显然有更好的解决方案)。
-
感谢您的观察 E.Serra,我只使用了其中的一些月份作为示例。
-
anky_91,您的解决方案效果很好。它打印了所有的列和行,并将月份名称更改为相应的数字。