python - 仅将月份从“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'
解决方案
字典的替代方法可以是在元组中使用索引(尽管使用字典进行散列可能更快):
months = (None, 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
integervalue = months.index(monthstring)
推荐阅读
- powerbi-embedded - 错误:嵌入 URL 对于这种情况无效。请使用 Power BI REST API 获取有效 URL
- c# - 我可以使用相同的方法运行 2 个程序集吗
- r - 查找两个连续的非零数据之间的差距
- java - JavaFX:我应该将场景保存在内存中吗?
- android - Android:添加新文件时强制扫描 getContentResolver()
- python - 如何将 Pandas 中数据框的所有值(不仅仅是一列而不是整个数据集)从“y”转换为 1,将“n”转换为 0?
- python - 数据框列的 t 检验
- vue.js - 如何使用 Vue Router 重定向路由?
- twitter-bootstrap - 如何限制 Bootstrap 4 中 p 标签的宽度以使其更具可读性?
- regex - 删除标点符号(保留字母数字和 unicode)Java