Eka
Eka

Reputation: 15002

how to take mean of the column of tuple

I have a tuple which I convert to numpay array

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

Like this

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

I want to take columns mean of this array ( 0.08+0+0.16)

tried this code

np.mean(ar, axis=0)

but its giving this error

 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

Upvotes: 0

Views: 306

Answers (1)

Grief
Grief

Reputation: 2040

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))

OUTPUT:

[ 0.08322511  0.23893048]

UPDATE

Shame on me! These lines are redundant:

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

Since there is a reassignment on the next line, ar becomes list instead of numpy.ndarray.

So either you should use just

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

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

or, you need:

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

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

OUTPUT:

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

Upvotes: 2

Related Questions