【问题标题】:How to calculate mean values over columns in a given data structure?如何计算给定数据结构中列的平均值?
【发布时间】:2017-02-17 13:23:37
【问题描述】:

我有以下数据结构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'))。

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

第三步(最终结果):

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

【问题讨论】:

  • 您的方法似乎很合理,尽管您实际上并不需要两个步骤。你尝试过什么,你在哪里卡住了?

标签: python arrays list numpy


【解决方案1】:

使用 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

【讨论】:

  • 将单个object 数组转换为二维float 数组是关键步骤。当元素为 objects 时,nan 替换不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 2019-06-23
  • 2017-09-24
  • 1970-01-01
相关资源
最近更新 更多