Numpy append数组不工作

问题描述:

为什么不附加所有列表?Numpy append数组不工作

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

它在做什么?不要只显示代码。显示结果并解释什么是错误的。 – hpaulj

numpy.append回报新NumPy的阵列,而你的代码显示,你认为这是增加新的值testarray。该阵列不附加在原地,新阵列必须被创建并填充数据,因此复制testarraytest[file]['subfile1']

此外,请注意,不需要循环使用键并通过其中一个键从字典中提取值。你也可以遍历的项目数组包含,包括键和值:

for key, value in test.items(): 
    print(value['subfile1']) 
    ... 

而不是反复串联列表到一个数组,收集在一个列表中的值,并构建阵列一次。这是更快,不易出错:

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

如果你一定要,建立反复名单:

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

注意这使:

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

你可以在每一步串联所有值都在一个1d数组中,而不是前面方法所做的2d数组。我们可以vstack去2d(它也使用concatenate)。我可以写append,但我宁愿不要。太多海报误用了它。