John Jay
John Jay

Reputation: 83

How to make a numpy array from raw input in python?

I need to write an array to a file using numpy, and I am trying to read in an array as raw input and convert it to an array. My problem seems to be coming from the line inarray = np.array(inlist), because the code is not returning an array. Here is my entire code:

import numpy as np
def write():
    inlist = raw_input('Please enter a square array of booleans.')
    print inlist
    inarray = np.array(inlist)
    print inarray
    dims = inarray.shape
    print dims
    dim = dims[0]
    name = open(name,'w')
    name.write(dims)
    dimint = int(dim)
    i = 0
    while i < dimint:
        name.write(inarray[i])
        i = i+1

return name

write()

Upvotes: 1

Views: 5839

Answers (2)

Roland Smith
Roland Smith

Reputation: 43495

The raw_input function returns a string.

What you could do is split() the string and map the a function over it:

In [1]: test = 'True False True False False'

In [2]: test.split()
Out[2]: ['True', 'False', 'True', 'False', 'False']

In [3]: map(lambda x: x in ['True', '1'], test.split())
Out[3]: [True, False, True, False, False]

The list in the lambda expression should contain all the values you want to recognize als True. It would be slightly better to use a function in map, so you can raise an exception when you find something that isn't unambiguously True or False.

Note that this only works well for a list of true/false values. For a nested and bracketed list, using ast.literal_eval as unutbu suggests is clearly the better solution:

In [1]: import ast

In [2]: ast.literal_eval('[[True], [False], [True]]')
Out[2]: [[True], [False], [True]]

But this will require you to use complete Python syntax. If you want to use 0 and 1 instead of True and False, remember to use the bool dtype:

In [5]: a = ast.literal_eval('[[1, 0, 1], [0, 1, 0], [0,0,1]]')

In [6]: np.array(a, dtype=bool)
Out[6]: 
array([[ True, False,  True],
       [False,  True, False],
       [False, False,  True]], dtype=bool)

Upvotes: 0

unutbu
unutbu

Reputation: 879611

raw_input is returning a string. If you feed this string directly to np.array, you get back a NumPy scalar:

In [17]: np.array('foo')
Out[17]: 
array('foo', 
      dtype='|S3')

In [18]: np.array('abl').shape
Out[18]: ()

In [19]: np.array('abl').dtype
Out[19]: dtype('|S3')

You need to convert the string into a Python object, such as a list of lists, before feeding it to np.array.

import ast
inarray = np.array(ast.literal_eval(inlist))

Upvotes: 1

Related Questions