[Tutor] create numpy array from list of strings
Danny Yoo
dyoo at cs.wpi.edu
Wed Jun 4 02:56:09 CEST 2008
> I actually thought this would be as simple as the 'load' command to get
> the data in from a file. But I just couldn't find the documentation
> online to do it once i have the data already 'inside' of python as a
> list. So, my options are:
Hello,
If you already have the values as a list of rows, where each row is a list
of numbers, then the 'array' function may be appropriate.
http://www.scipy.org/Cookbook/BuildingArrays
I see that you already know about array() from your second solution.
> 1) write the data block out to a temporary file and read it in using 'load'
> - which is really simple (see: http://www.scipy.org/Cookbook/InputOutput)
Alhtough it's simple, if you can avoid I/O, do so: touching disk can raise
its own problems. I like your second approach much better.
> 2) I've done the following, but I doubt it is the most efficient method:
>
> tempDATA=[]
> for i in data[stind:-1]: #this is the data block from the file
> tempDATA.append([float(j) for j in i.split()])
>
> outdata=array(tempDATA).transpose()
>
> Is there a better way?
This looks good.
I'm not sure I understand the transpose() call, although I suspect it's
because that's the next step you want to do to process your array.
But just to follow up on what you said earlier:
> I'm not really trying to create a function.
It's actually very easy to turn what you have there into a function. I'd
recommend doing so. Here's what it looks like.
#######################################################
def convert(data):
tempDATA = []
for i in data:
tempDATA.append([float(j) for j in i.split()])
return array(tempDATA)
#######################################################
To get back the same behavior as your code above, you can call this
function as:
outdata = convert(data[stind:-1]).transpose()
Functions give you a way to bundle up a collection of related operations.
More importantly, that 'tempDATA' variable doesn't stick around hanging
out in space: it only lives in the convert() function.
More information about the Tutor
mailing list