我有一个字典列表如下:
>>>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
数据类型,因为这将引入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
现在我们需要对字典键进行排序,因为调用 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}]
关于python - Pandas 重采样的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244127/