【问题标题】:change only the month from 'jan' to 1, ' feb' to 2, ' mar' to 3...'dec' to 12 [duplicate]仅将月份从'jan'更改为1,'feb'更改为2,'mar'更改为3 ...'dec'更改为12 [重复]
【发布时间】: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,您的解决方案效果很好。它打印了所有的列和行,并将月份名称更改为相应的数字。

标签: python pandas


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以使用以下代码将月份转换为整数

    import pandas as pd
    
    def GetMonthInInt(month):
        MonthInInts = pd.Series([1,2,3,4,5,6,7,8,9,10,11,12],index=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'])
        return MonthInInts[month.lower()]
    
    data = pd.DataFrame(['Oct','Nov','Mar','Feb','Jan','Dec','Aug','Sep'],columns=['Month'])
    data['MonthInInt']= data['Month'].apply(GetMonthInInt)
    print(data)
    

    您将通过上面的示例代码获得此输出

      Month  MonthInInt
    0   Oct          10
    1   Nov          11
    2   Mar           3
    3   Feb           2
    4   Jan           1
    5   Dec          12
    6   Aug           8
    7   Sep           9
    

    希望,这可以解决您将月份转换为整数的问题。

    【讨论】:

      【解决方案3】:

      使用datetime:

      df['month'] = pd.to_datetime(df['month'],format='%b').dt.month
      

      或者:

      import calendar
      df['month'] = df['month'].str.title().apply(list(calendar.month_abbr).index)
      

      【讨论】:

        猜你喜欢
        • 2015-06-19
        • 2020-07-17
        • 2023-02-06
        • 2021-04-15
        • 1970-01-01
        • 2010-12-30
        • 1970-01-01
        • 2020-04-02
        • 1970-01-01
        相关资源
        最近更新 更多