如何取元组列的意思

时间:2016-03-17 18:47:16

标签: python arrays numpy

我有一个元组,我将其转换为numpay数组

dt=np.dtype('float,float') 
ar=np.array(val,dtype=dt)

喜欢这个

ar=[(0.08181818181818182, 0.394023569023569) (0.0, 0.0)
 (0.16785714285714287, 0.3227678571428571)]

我想取这个数组的平均值(0.08 + 0 + 0.16)

试过这段代码

np.mean(ar, axis=0)

但它给出了这个错误

 print np.mean(ar, axis=0)
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 2878, in mean
    out=out, keepdims=keepdims)
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/_methods.py", line 65, in _mean
    ret = umr_sum(arr, axis, dtype, out, keepdims)
TypeError: cannot perform reduce with flexible type

1 个答案:

答案 0 :(得分:2)

import numpy as np

dt=np.dtype('float,float')
ar=np.array([], dtype=dt)

ar=[(0.08181818181818182, 0.394023569023569), (0.0, 0.0),
    (0.16785714285714287, 0.3227678571428571)]

print(np.mean(ar, axis=0))

<强>输出

[ 0.08322511  0.23893048]

<强>更新

对我感到羞耻!这些行是多余的:

dt=np.dtype('float,float')
ar=np.array([], dtype=dt)

由于下一行有重新分配,ar变为list而不是numpy.ndarray

所以要么你应该只使用

ar=[(0.08181818181818182, 0.394023569023569), (0.0, 0.0),
    (0.16785714285714287, 0.3227678571428571)]

print(np.mean(ar, axis=0))

或者,您需要:

ar = np.array(
    [
        (0.08181818181818182, 0.394023569023569),
        (0.0, 0.0),
        (0.16785714285714287, 0.3227678571428571)
    ])

print(type(ar))
print(np.mean(ar, axis=0))

<强>输出

<class 'numpy.ndarray'>
[ 0.08322511  0.23893048]