【问题标题】:Numpy append array isn't workingNumpy追加数组不起作用
【发布时间】:2016-12-05 02:37:08
【问题描述】:

为什么不附加所有列表?

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)

【问题讨论】:

  • 它在做什么?不要只显示代码。显示结果并说明问题所在。

标签: python numpy


【解决方案1】:

numpy.append 返回一个新的 NumPy 数组,而您的代码显示您认为它正在向 testarray 添加新值。该数组不是就地附加的,必须创建一个新数组并用数据填充,从而复制testarraytest[file]['subfile1']

另外,请注意,无需循环键并通过这些键之一从字典中提取值。您可以遍历数组包含的 items,包括键和值:

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

【讨论】:

    【解决方案2】:

    与其重复地将列表连接到一个数组,不如收集一个列表中的值,然后只构建一次数组。它更快,更不容易出错:

    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 [518]: data=[]
    In [519]: for f in test.keys():
         ...:     data.append(test[f]['subfile1'])
    

    你可以在每一步连接:

    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 去二维(它也使用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 来写这个,但我不想这样做。太多海报滥用它。

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2016-04-08
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2015-06-04
      • 2016-11-16
      • 2018-01-14
      • 2015-02-21
      相关资源
      最近更新 更多