【问题标题】:AttributeError: 'numpy.ndarray' object has no attribute 'median'AttributeError:“numpy.ndarray”对象没有属性“中位数”
【发布时间】:2017-02-27 23:28:12
【问题描述】:

我可以对一个 numpy 数组执行一些统计,但“中位数”返回一个属性错误。当我执行“dir(np)”时,我确实看到了列出的中值方法。

(newpy2) 7831c1c083a2:src scaldara$ python
Python 2.7.12 |Continuum Analytics, Inc.| (default, Jul  2 2016,   17:43:17) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on     darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org

>>> import numpy as np
>>> print(np.version.version)
1.11.2
>>> a = np.array([1,2,3,4,5,6,7,8,9,10])
>>> print(a)
[ 1  2  3  4  5  6  7  8  9 10]
>>> print(a.min())
1
>>> print(a.max())
10
>>> print(a.mean())
5.5
>>> print(a.std())
2.87228132327
>>> print(a.median())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'median'
>>> 

【问题讨论】:

  • 错误很明显,您需要执行 np.median(a),因为该方法不是 numpy.ndarray 的成员,而是 numpy 中的方法

标签: python numpy


【解决方案1】:

虽然numpy.ndarraymeanmaxstd等方法,但它没有median方法。有关ndarray 可用的所有方法的列表,请参阅numpy documentation for ndarray

它可以作为一个将数组作为参数的函数使用:

>>> import numpy as np
>>> a = np.array([1,2,3,4,5,6,7,8,9,10])
>>> np.median(a)
5.5

正如您将在 the documentation for ndarray.mean 中看到的,ndarray.meannp.mean 是“等效函数”,所以这只是语义问题。

【讨论】:

  • 为什么他们选择不将其添加为方法?
  • 人们应该在 github 上添加一个 issue,以便让 median() 作为一种方法可用,就像其他函数(mean、std、max、...)一样。没有理由排除中位数。
猜你喜欢
  • 2020-12-03
  • 2020-11-29
  • 2020-10-06
  • 2018-01-25
  • 2016-06-29
  • 2020-03-25
  • 2013-12-07
  • 2017-10-16
  • 2020-02-23
相关资源
最近更新 更多