numpy的追加数组不起作用 [英] Numpy append array isn't working

查看:109
本文介绍了numpy的追加数组不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不附加所有列表?

Why isn't it appending all the lists?

test = {'file1':{'subfile1':[1,2,3],'subfile2':[10,11,12]},'file5':{'subfile1':[4,678,6]},'file2':{'subfile1':[4,78,6]},'file3':{'subfile1':[7,8,9]}}
testarray = np.array([50,60,70])
for file in test.keys():
    print(test[file]['subfile1'])
    subfile1 = np.append(testarray, test[file]['subfile1'])
print(subfile1)

推荐答案

不要重复将列表连接到数组,而是将列表中的值收集起来,然后仅构建一次数组.它更快,而且更不容易出错:

Rather than repeatedly concatenating lists to an array, collect the values in a list, and build the array just once. It is faster, and less prone to errors:

In [514]: test
Out[514]: 
{'file1': {'subfile1': [1, 2, 3], 'subfile2': [10, 11, 12]},
 'file2': {'subfile1': [4, 78, 6]},
 'file3': {'subfile1': [7, 8, 9]},
 'file5': {'subfile1': [4, 678, 6]}}
In [515]: data=[test[f]['subfile1'] for f in test]
In [516]: data
Out[516]: [[1, 2, 3], [4, 78, 6], [7, 8, 9], [4, 678, 6]]
In [517]: np.array(data)
Out[517]: 
array([[  1,   2,   3],
       [  4,  78,   6],
       [  7,   8,   9],
       [  4, 678,   6]])

如果必须,请迭代构建列表:

If you must, build the list iteratively:

In [518]: data=[]
In [519]: for f in test.keys():
     ...:     data.append(test[f]['subfile1'])

您可以在每个步骤中串联:

You could concatenate at each step:

In [521]: testarray=np.array([50,60,70])
In [522]: for file in test.keys():
     ...:     testarray = np.concatenate((testarray, test[file]['subfile1']))
     ...:     
In [523]: testarray
Out[523]: 
array([ 50,  60,  70,   1,   2,   3,   4,  78,   6,   7,   8,   9,   4,  678,   6])

请注意,这会将所有值放置在一个1d数组中,而以前的方法则将其放置在2d数组中.我们可以vstack进行2d处理(它也使用concatenate).

Notice this puts all values in one 1d array, as opposed to a 2d array that the previous methods did. We can vstack to go 2d (it too uses concatenate).

In [525]: testarray=np.array([50,60,70])
In [526]: for file in test.keys():
     ...:     testarray = np.vstack((testarray, test[file]['subfile1']))
     ...:     
     ...:     
In [527]: testarray
Out[527]: 
array([[ 50,  60,  70],
       [  1,   2,   3],
       [  4,  78,   6],
       [  7,   8,   9],
       [  4, 678,   6]])

我也可以用append编写,但是我宁愿不这样做.太多的海报滥用了它.

I could also write this with append, but I'd rather not. Too many posters misuse it.

这篇关于numpy的追加数组不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆