【问题标题】:Python: fill in missing months with zeroPython:用零填充缺失的月份
【发布时间】:2011-08-21 05:34:33
【问题描述】:

我有一个字典列表,如下所示。每个字典都保存特定月份的总数。如果一个月没有出现在列表中,例如一月,那么它的总数应该为零。

q = [{'total_item': 3, 'month': u'02'}, {'total_item': 1, 'month': u'03'}, {'total_item': 1, 'month': u'05'}, {'total_item': 5, 'month': u'06'}, {'total_item': 6, 'month': u'07'}, {'total_item': 1, 'month': u'10'}, {'total_item': 1, 'month': u'12'}]

我想把上面的数据结构转换成一个简单的列表,其中序数位置代表月份,值代表项目总数。

[0, 3, 1, 0, ...] # 12 entries in total - one for each month

即一月是 0,二月是 3,三月是 1 等等。

我知道我可以使用这样的方法来获取当前值:

result = [r['total_item'] for r in q]

但是如何为不存在的月份创建零值条目?

【问题讨论】:

    标签: python


    【解决方案1】:
    result = [0]*12
    for r in q:
        result[int(r['month'])-1] = r['total_item']
    

    【讨论】:

    • 这会在 12 月产生 IndexError :)
    • 不应该,如果一月是0...但显然输入数据使用一月作为1,这很容易修复。
    【解决方案2】:

    只需遍历列表,并根据月份的值进行分配。

    total_items = [0]*12
    for d in q:
      month = int(d['month'], 10)
      total_items[month-1] = d['total_item']
    

    【讨论】:

      【解决方案3】:

      使用这个:

      class MyDict(dict):
          def __missing__(self, key):
              self[key] = 0
              return self[key]
      

      然后你可以使用这个对象而不是普通的字典。它的行为和它一样,但是当你访问一个不存在的项目时,它会创建一个值为 0 的项目。

      【讨论】:

      • 为什么不使用collections.defaultdict
      【解决方案4】:

      尝试:

      >>> months = [0] * 12
      >>> for r in q: months[int(r['month'])-1] = r['total_item']
      >>> months
      [0, 3, 1, 1, 1, 5, 6, 6, 0, 1, 1, 1]
      

      【讨论】:

        【解决方案5】:

        还有另一种方法...将现有月份映射到它们的 total_item 值,然后使用 dict.get() 默认为 0

        nitems = dict((int(x['month']), x['total_item']) for x in q)
        result = [nitems.get(i, 0) for i in range(1, 13)]
        

        【讨论】:

          【解决方案6】:

          更短的方法(Python ≥ 2.7,因为 dict 理解):

          >>> d={int(i["month"]):i["total_item"] for i in q} #create a easier to use dict
          >>> d
          {2: 3, 3: 1, 5: 1, 6: 5, 7: 6, 10: 1, 12: 1}
          >>> [d.get(i,0) for i in range(1,13)] #d.get(i,0) returns 0 if i not in dict
          [0, 3, 1, 0, 1, 5, 6, 0, 0, 1, 0, 1]
          

          【讨论】:

            【解决方案7】:

            也许您可能想使用 scikits.timeseries:

            http://pytseries.sourceforge.net/

            例如:

            import scikits.timeseries as TS
            aDate = TS.Date('M', '2010-01-01')
            myTS = TS.time_series(myData, start_date = aDate, freq = 'M')
            

            从那里您可以用零填充缺失值并导出(我相信使用 myTS.fill(0))。

            【讨论】:

              猜你喜欢
              • 2023-02-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-08-23
              • 1970-01-01
              • 2018-03-04
              • 1970-01-01
              • 2020-01-13
              相关资源
              最近更新 更多