Python:将NumPy列表转换为数组并进行vstack

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

我使用

new_array = numpy.vstack([datas])

获得 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)]]

但我更喜欢的是:
(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)

我应该使用哪个函数?

谢谢。


我相信在 vstack 调用中您不需要额外的 []。只需尝试:new_array = numpy.vstack(datas) - ely
我试图去掉[],但是我收到了一个错误信息:“ValueError: all the input array dimensions except for the concatenation axis must match exactly. - user2858910
如果每个潜在的行具有不同的长度,那么您将无法垂直堆叠数据。因此,首先需要弄清楚为什么数据具有不同的长度,如果它们在概念上应该是来自同一矩阵的行。 - ely
感谢您指出长度问题,我会找出或修复长度以适合要求。 - user2858910
如果这些数组代表不同的声音文件(它们自然会具有不同的长度),您还可以考虑使用 pandas.DataFrame 来存储和操作它们。 - metakermit
显示剩余2条评论
1个回答

5
以下内容对我有效,因此您问的datas元素不像您的问题所暗示的是平面数组,潜在行的长度不同(这证明是原因,请参见评论),或者您正在使用有问题的旧版本vstack中的1维对象? (虽然我认为这不太可能)
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]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接