2017-02-17 52 views
0

我有以下数据结构ds如何计算给定数据结构中列的平均值?

{('AD', 'TYPE_B', 'TYPE_D'): [array([84.0, 85.0, 115.0], dtype=object), array([31.0, 23.0, 599.0], dtype=object), array([75.0, 21.0, nan], dtype=object), array([59.0, 52.0, 29.0], dtype=object)],('AD', 'TYPE_A', 'TYPE_N'): [array([84.0, 85.0, 115.0], dtype=object), array([31.0, 23.0, 599.0], dtype=object), array([75.0, 21.0, 300.0], dtype=object), array([59.0, 52.0, 29.0], dtype=object)]} 

我需要在第一列,第二列和每每个键(即('AD', 'TYPE_B', 'TYPE_D')('AD', 'TYPE_A', 'TYPE_N'))第3列来估计平均值。

array([75.0, 21.0, nan]像有些阵列包含nan串,我想通过0

例如替代,对于键('AD', 'TYPE_B', 'TYPE_D')以下结果应达到(解释步步):

步骤1:

84.0 85.0 115.0 
31.0 23.0 599.0 
75.0 21.0 nan 
59.0 52.0 29.0 

步骤2:

84.0 85.0 115.0 
31.0 23.0 599.0 
75.0 21.0 0 
59.0 52.0 29.0 

步骤3(最终结果):

('AD', 'TYPE_B', 'TYPE_D'): [62.25, 45.25, 185.75] 
+0

虽然您并不需要两个步骤,但您的方法似乎是合理的。你有什么尝试,你卡在哪里? – zwer

回答

3

使用内置函数从numpy的。

import numpy as np 

ds = {('AD', 'TYPE_B', 'TYPE_D'): [np.array([84.0, 85.0, 115.0], dtype=object), 
            np.array([31.0, 23.0, 599.0], dtype=object), 
            np.array([75.0, 21.0, np.nan], dtype=object), 
            np.array([59.0, 52.0, 29.0], dtype=object)], 
     ('AD', 'TYPE_A', 'TYPE_N'): [np.array([84.0, 85.0, 115.0], dtype=object), 
            np.array([31.0, 23.0, 599.0], dtype=object), 
            np.array([75.0, 21.0, 300.0], dtype=object), 
            np.array([59.0, 52.0, 29.0], dtype=object)]} 

for key in ds.keys(): 
    #first cast to float and replace nan 
    item = np.nan_to_num(np.asarray(ds[key], dtype=np.float64)); 
    #calculate the mean 
    mean = np.mean(item, axis=0) 
    #store it in the dictionary 
    ds[key] = mean 

print ds 
+1

将单个'object'数组转换为2d'float'数组是一个关键步骤。当元素是“对象”时,'nan'替换不起作用。 – hpaulj