How to calculate mean values over columns in a given data structure?

后端 未结 1 553
南笙
南笙 2021-01-28 06:23

I have the following data structure ds:

{(\'AD\', \'TYPE_B\', \'TYPE_D\'): [array([84.0, 85.0, 115.0], dtype=object), array([31.0, 23.0, 599.0], dty         


        
相关标签:
1条回答
  • 2021-01-28 07:08

    use the built-in functions from 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
    
    0 讨论(0)
提交回复
热议问题