簡體   English   中英

熊貓重新采樣的問題

[英]Issue with Pandas resampling

我有以下詞典列表:

>>>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 astype ,因為這將為缺失值引入NaN值,您可以使用astype來解決此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}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM