Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: numpy list to array and vstack

from scipy.io.wavfile import read
filepath = glob.glob('*.wav')
rates = []
datas = []
for fp in filepath:
    rate, data = read(fp)
    rates.append(rate)
    datas.append(data)

I get a list 'datas' which is :

[array([0, 0, 0, ..., 0, 0, 0], dtype=int16), array([0, 0, 0, ..., 0, 0, 1], dtype=int16), array([0, 0, 0, ..., 0, 0, 0], dtype=int16),..., array([0, 0, 0, ..., 0, 0, 0], dtype=int16)]

and I use

new_array = numpy.vstack([datas])

to get the new_array :

[[array([0, 0, 0, ..., 0, 0, 0], dtype=int16)
  array([0, 0, 0, ..., 0, 0, 1], dtype=int16)
  array([0, 0, 0, ..., 0, 0, 0], dtype=int16)
  ...
  array([0, 0, 0, ..., 0, 0, 0], dtype=int16)]]

But I really prefer one is :

(array([[ 0,  0,  0, ...,  0,  0,  0],
   [ 0,  0,  0, ...,  0,  0,  1],
   [ 0,  0,  0, ...,  0,  0,  0],
   ...,        
   [ 0,  0,  0, ...,  0,  0,  0]], dtype=int16)

Which function should I use?

Thanks.

like image 945
user2858910 Avatar asked Oct 08 '13 17:10

user2858910


1 Answers

The following works for me, so either the elements of datas are not flat arrays like your question suggests, the potential rows have different lengths (this turned out to be the reason, see comments), or perhaps you are using an older version that has a problem with a 1-dimensional object in vstack? (although I think that is unlikely)

In [14]: datas = [np.asarray([0, 0, 0, 0, 0, 0]), np.asarray([0, 0, 0, 0, 0, 1])]

In [15]: datas
Out[15]: [array([0, 0, 0, 0, 0, 0]), array([0, 0, 0, 0, 0, 1])]

In [16]: datas[0].shape
Out[16]: (6,)

In [17]: np.vstack(datas)
Out[17]:
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1]])
like image 194
ely Avatar answered Oct 13 '22 02:10

ely