如何计算给定数据结构中列的平均值?

时间:2017-02-17 13:23:38

标签: python arrays list numpy

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

第3步(最终结果):

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

1 个答案:

答案 0 :(得分:3)

使用numpy的内置函数。

import {Component, NgZone} from "@angular/core";

@Component({
  selector: 'app',
  templateUrl: './app.component.html'
})

export class MyComponent {
  myValue: string;

  constructor(private ngZone: NgZone) {
  }

  getData() {
    const self = this;
    myAsyncCall().then(result => {
      ngZone.run(() => {
        self.myValue = result;
      });
    });
  }
}