我有以下词典列表:

>>>L=[
   {
   "timeline": "2014-10",
   "total_prescriptions": 17
   },
   {
   "timeline": "2014-11",
   "total_prescriptions": 14
   },
   {
   "timeline": "2014-12",
   "total_prescriptions": 8
  },
  {
  "timeline": "2015-1",
  "total_prescriptions": 4
  },
  {
  "timeline": "2015-3",
  "total_prescriptions": 10
  },
  {
  "timeline": "2015-4",
  "total_prescriptions": 3
  }
  ]


我需要做的是填补缺失的月份,在这种情况下,2015年2月总处方为零。我使用Pandas的方法如下:

>>> df = pd.DataFrame(L)
>>> df.index=pd.to_datetime(df.timeline,format='%Y-%m')
>>> df
           timeline  total_prescriptions
timeline
2014-10-01  2014-10                  17
2014-11-01  2014-11                  14
2014-12-01  2014-12                   8
2015-01-01  2015-1                    4
2015-03-01  2015-3                   10
2015-04-01  2015-4                    3

>>> df = df.resample('MS').fillna(0)
>>> df
            total_prescriptions
timeline
2014-10-01                   17
2014-11-01                   14
2014-12-01                    8
2015-01-01                    4
2015-02-01                    0
2015-03-01                   10
2015-04-01                    3


到目前为止,一切都很好..只是我想要的..现在我需要将此数据帧转换回字典列表。.这就是我的方法:

>>> response = df.T.to_dict().values()
>>> response
[{'total_prescriptions': 0.0},
 {'total_prescriptions': 17.0},
 {'total_prescriptions': 10.0},
 {'total_prescriptions': 14.0},
 {'total_prescriptions': 4.0},
 {'total_prescriptions': 8.0},
 {'total_prescriptions': 3.0}]


排序丢失,时间轴丢失,total_prescriptions成为int的十进制值。出了什么问题?

最佳答案

首先,由于重新采样,到十进制的转换实际上是float dtype,因为这将为丢失的值引入NaN值,您可以使用astype修复此问题,然后可以恢复“时间轴”列,该列会丢失无法弄清楚如何对str重新采样,因此我们可以将strftime应用于索引:

In [80]:
df = df.resample('MS').fillna(0).astype(np.int32)
df['timeline'] = df.index.to_series().apply(lambda x: dt.datetime.strftime(x, '%Y-%m'))
df

Out[80]:
            total_prescriptions timeline
timeline
2014-10-01                   17  2014-10
2014-11-01                   14  2014-11
2014-12-01                    8  2014-12
2015-01-01                    4  2015-01
2015-02-01                    0  2015-02
2015-03-01                   10  2015-03
2015-04-01                    3  2015-04


现在我们需要对dict键进行排序,因为调用values会失去排序顺序,并且我们可以执行列表理解以返回原始格式:

In [84]:
d = df.T.to_dict()
[d[key[0]] for key in sorted(d.items())]

Out[84]:
[{'timeline': '2014-10', 'total_prescriptions': 17},
 {'timeline': '2014-11', 'total_prescriptions': 14},
 {'timeline': '2014-12', 'total_prescriptions': 8},
 {'timeline': '2015-01', 'total_prescriptions': 4},
 {'timeline': '2015-02', 'total_prescriptions': 0},
 {'timeline': '2015-03', 'total_prescriptions': 10},
 {'timeline': '2015-04', 'total_prescriptions': 3}]

09-30 21:11