将列表转换为NumPy数组 [英] Issue converting list to NumPy array
问题描述
我有一个包含2000行和88200列的列表:
I have a list that consits of 2000 rows and 88200 columns:
testlist = list(split_audio_to_parts(audio, self.sample_rate, self.audio_index))
调试testlist
输出给出
[array([-0.00683594, -0.00689697, -0.00708008, ..., 0. ,
0. , 0. ]), array([-0.01287842, -0.01269531, -0.01257324, ..., 0. ,
0. , 0. ]), array([0.02288818, 0.01940918, 0.01409912, ..., 0. , 0. ,
0. ]), array([0.00772095, 0.00671387, 0.00695801, ..., 0. , 0. ,
0. ]),
,依此类推.
split_audio_to_parts
是一个功能:
and so on.
split_audio_to_parts
is a function:
def split_audio_to_parts(x, sample_rate, audio_index):
for i, row in audio_index.iterrows():
x_part = x[int(row['start_samples']):int(row['end_samples'])]
yield x_part
当我尝试使用samples = np.array(testlist)
或samples = np.asarray(testlist)
将其转换为numpy数组时,尽管调试显示testlist
包含2000个条目(具有88200个位置),但它却给出了形状数组(2000).为什么这样?我正在使用64位numpy和64位Python 3.6.5.
When I try to convert it to numpy array using samples = np.array(testlist)
or samples = np.asarray(testlist)
, it gives me array of shape (2000,), although debugging shows that testlist
consits of 2000 entries with 88200 positions. Why so? I'm using 64bit numpy and 64bit Python 3.6.5.
推荐答案
问题是testlist
是不同大小的数组的列表.例如,检查此代码:
The problem is testlist
is a list of different size arrays. For example checkout this code:
>>>import numpy as np
>>>import random
>>>random.seed(3240324324)
>>> y=[np.array(list(range(random.randint(1,3)))) for _ in range(3)]
>>> y
[array([0, 1, 2]), array([0, 1, 2]), array([0])]
>>> np.array(y)
array([array([0, 1, 2]), array([0, 1, 2]), array([0])], dtype=object)
>>> np.array(y).shape
(3,)
,数组将是object
类型,而不是float.唯一可行的方法是使用相同大小的数组.
and the array would be of object
type instead of float. the only way for this to work is having same sized arrays.
如果您确实需要将这些行以某种方式填充到数组中,则可以用零填充,例如:
If you really need to stuff these rows somehow into an array you can pad with zeros, for example:
>>> size = y[max(enumerate(y),key=lambda k:k[1].shape)[0]].shape[0]
>>> z=[np.append(x,np.zeros(size-x.shape[0])) for x in y]
>>> z
[array([ 0., 1., 2.]), array([0, 1, 2]), array([0, 0, 0])]
>>>np.array(z).shape
(3, 3)
但是您必须决定如何进行填充.
but you would have to decide how you do this padding.
这篇关于将列表转换为NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!