jeudi 8 juin 2017

How to select specific row column pairs in numpy array which have specific value?

I am trying to have a numpy array with random numbers from 0 to 1:

import numpy as np
x = np.random.random((3,3))

yields

[[ 0.11874238  0.71885484  0.33656161]
 [ 0.69432263  0.25234083  0.66118676]
 [ 0.77542651  0.71230397  0.76212491]]

And, from this array, I need the row,column combinations which have values bigger than 0.3. So the expected output should look like:

(0,1),(0,2),(1,0),(1,2),(2,0),(2,1),(2,2)

To be able to extract the item (the values of x[row][column]),and tried to write the output to a file. I tried the following command:

with open('newfile.txt', 'w') as fd:
    for row in x:
        for item in row:
            if item > 0.3:
                print(item)
                for row in item:
                    for col in item:
                        print(row,column,'\n')
                        fd.write(row,column,'\n')

However, it raises an error :

TypeError: 'numpy.float64' object is not iterable

Also, I searched but could not find how to start the numpy index from 1 instead of 0. For example, the expected output would look like this:

 (1,2),(1,3),(2,1),(2,3),(3,1),(3,2),(3,3)

Do you know how to get these output?




Aucun commentaire:

Enregistrer un commentaire