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()
share|improve this question
if the code does not return an array, what does it return? – Aswin Murugesh 2 days ago

2 Answers

up vote 1 down vote accepted

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))
share|improve this answer

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)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.