3

This code is set up to read two columns of data, and then print the first column into the first numpy array and then the second column into the second numpy array.

def read2coldata(filename):

    import numpy
    b = []
    f = open(filename,"r")
    lines = f.readlines()
    f.close()
    for line in lines:
        a = line.split()
        for i in a:
            b.append(i)
    return (numpy.array(b[::2]),numpy.array(b[1::2]))

However this gives:

(array(['1.5', '8', '16', '17'], dtype='|S3'), array(['4', '5', '6', '6.2'], dtype='|S3'))

How do I get rid of the dtype="|S3" parts to just leave:

(array(["1.5","8","16","17"], array(["4","5","6","6.2"])
1
  • If you convert you arrays to floats, the data type specifier will go away. Considering your strings look like they will need to be converted to numerical values you might want to look into that. You can use x.astype(float). Commented Dec 8, 2012 at 2:37

1 Answer 1

5

the dtype="S3" you don't want to "go away". When you print a numpy array it gives you the type of the data in it. it isn't part of the data, it is information about how the data is stored and understood by the program.

In your particular example, you read number, so you probably want to use them afterwards in computation or whatever, in which case you'll want the data to be understood as number (floats in you case).

For the moment they are stored as strings, and that's why you see dtype="S3" which essentially means string type of size 3 or less. (IIRC)

I suggest to you an alternative to your function : numpy.genfromtxt is a function to load data from a txt file into a numpy array.

The documentation is quite good and you'll find it very useful if you spend the 20 minutes to understand the parameters.

array1 = numpy.genfromtxt('path_to_my_file.txt', usecols=0)
array2 = numpy.genfromtxt('path_to_my_file.txt', usecols=1)

This should get you started.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.