首页 > 解决方案 > 将 numpy 数组存储在列表中

问题描述

我想自动化在 numpy 中加载一些 ASCII 数据文件的过程,以便绘制它们。文件名通过终端提供给程序,内容被加载并保存在列表中。所以基本上这个想法是有一个包含 numpy 数组的列表,我可以稍后通过索引调用这些数组来绘制每个单独的数据。我遇到的问题是索引不适用于我制作的这些列表

    subplots_array = [[0,0],[0,0],[0,0],[0,0]]
    subplots_axes = [0,0,0,0] #this array will allow to create subplots for ''' 
                              # each of the above data
    fig = plt.figure()
    counter = 0
    for x in arguments_list:
        for filename in glob.glob(x):  
            mydata = np.loadtxt(filename)
            subplots_array[counter] = mydata # This loads the data from files 
            #specified in arguments argv into a subplot array as numpy sub-array
            counter += 1

    counter = 0    

    for x in subplots_array: 
         subplots_axes[counter] = fig.add_subplot(counter+1, 1, 1) 
         subplots_axes[counter].scatter(subplots_array[counter][:, 0]), subplots_array[counter][:, 1], s = 12, marker = "x")
         counter = counter + 1

这是我得到的错误。有趣的是,如果我用数字索引(如 0 或 1 或 2 等)替换“计数器”,尽管计数器也被定义为索引,但数据绘制正确。所以我没有想法。

Traceback (most recent call last):
  File "FirstTrial.py", line 89, in <module>
    subplots_axes[counter].scatter(subplots_array[counter][:,0], subplots_array[counter][:, 1], s = 12, marker = "x")
TypeError: list indices must be integers or slices, not tuple

我希望这是足够的描述来帮助我解决问题。

标签: listnumpyindexing

解决方案


您的缩进已关闭,如果没有您的文件,我将无法重现您的代码。但这是我认为正在发生的事情:

In [1]: subplots_array = [[0,0],[0,0],[0,0],[0,0]]                                                     
In [2]: subplots_array[0]=np.ones((2,3))   # one or more counter loops

索引与counter==0作品:

In [4]: subplots_array[0][:,0]                                                                         
Out[4]: array([1., 1.])

但你的下一个计数器值的错误:

In [5]: subplots_array[1][:,0]                                                                         
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-0b654866bdee> in <module>
----> 1 subplots_array[1][:,0]

TypeError: list indices must be integers or slices, not tuple

subplot_array在这里,我用二维数组替换了 的一个元素,但不理会其他元素。它们被命名为列表:

In [6]: subplots_array                                                                                 
Out[6]: 
[array([[1., 1., 1.],
        [1., 1., 1.]]), [0, 0], [0, 0], [0, 0]]

所以问题不在于counter类型本身,而在于下一级索引。


推荐阅读