当前位置: 动力学知识库 > 问答 > 编程问答 >

2d array out of bounds python

问题描述:

I am trying to put values between two 2d string arrays.

atts is a dictionariy, have the correct values (I checked).

I have a loop, where the first and second interations work as expected, copying the arrays, but the third iteration (where key is '3rd' and its value is 301 which is bigger than the other two keys) doesn't work. it actually copies all as expected, but gives me a warning "index 301 is out of bounds for axis 0 with size 301". it's really confusing, since the loop does the same for every key so why won't it work only for the third iteration?

for key in atts:

cutTable = array(range( (atts[key]) * (len(Table[0])-1)), dtype='S10').reshape( (atts[key]),(len(Table[0])-1))

m=0

for i in range(len(Table)):

if(Table[i][index_to_cut] == key):

m+=1

beenHere= False

for k in range(len(Table[0])):

if (k==index_to_cut):

beenHere = True

continue

else:

if(beenHere):

cutTable[m-1][k-1] = Table[i][k]

else:

cutTable[m-1][k] = Table[i][k]

I printed dict atts for youall:

atts: { '2nd': 101, '1st':111, '3rd':301, 'crew':547)

I'm kinda stuck and I don't know how to solve this, if anyone knows I will be grateful..

网友答案:

You are not using Numpy correctly. The strength of Numpy is avoiding slow loops in Python code and replacing them by internal loops of Numpy structures written in C, Fortran, or C++.

Even in pure Python a for index in range(len(sequence)) just to use index for indexing sequence is an anti pattern because you can iterate over the elements of sequence directly. The variable i is unnecessary for instance. And when the index is needed in addition to the value at that index there's the enumerate() function.

Incrementing m is placed suboptimal. If moved to the end of the if branch you don't need to subtract one for storing values in cut_table.

Pure Python could look like this (np is the numpy module):

for key, value in atts.iteritems():
    cut_table = np.zeros((value, len(table[0] - 1)), dtype='S10')
    j = 0
    for row in table:
        if row[index_to_cut] == key:
            for j, value in enumerate(row):
                cut_table[j][j - (j > index_to_cut)] = value
            j += 1
    assert j == value

But assuming the cut_table array is as long as there are key values in table you should really actually use Numpy to solve this, which may look like this:

for key, value in atts.iteritems():
    cut_table = np.delete(
        table[table[:, index_to_cut] == key], index_to_cut
    )
    assert len(cut_table) == value

This selects all rows from table where the value in column index_to_cut is equal to key and removes that very column. Without any slow loop in Python code.

分享给朋友:
您可能感兴趣的文章:
随机阅读: