2

I have a text file that contains data in two columns, each of which I want to read into Python as a list.

For example :

       2500.3410      -0.60960758
       2505.5803       -1.3031826
       2510.8197      -0.64067196
       2516.0593       -1.0230898
       2521.2991      -0.20078891

I want to create two lists, one containing the data from column 1 and the other column 2, but I don't know how to tell Python to do this.

E.g.

list1 = [2500.3410, 2505.5803, 2510.8197, 2516.0593, 2521.2991]      

I have opened the file in the shell and can read in the data, as above, but I'm stuck when it comes to creating the lists.

2 Answers 2

1

First of all you have to read the text file in Python , for an instance if you have a file named record.txt containg dataset,

file <- open('record.txt')

now you have to read the file line by line :

lst = [] 

stores the whole file as a list of list and each inner list represents an instance

for line in file:
    lst.append([ float(x) for x in line.split()])

now you can extract the column1 as a list and column 2 as a list by following comprehension

column1 = [ x[0] for x in lst]
column2 = [ x[1] for x in lst]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use zip function and float within map :

zip(*[map(float,line.split()) for line in open('in_file')])

Demo:

>>> s="""       2500.3410      -0.60960758
...        2505.5803       -1.3031826
...        2510.8197      -0.64067196
...        2516.0593       -1.0230898
...        2521.2991      -0.20078891"""
>>> 
>>> [i.split() for i in s.split('\n')]
[['2500.3410', '-0.60960758'], ['2505.5803', '-1.3031826'], ['2510.8197', '-0.64067196'], ['2516.0593', '-1.0230898'], ['2521.2991', '-0.20078891']]
>>> zip(*[map(float,i.split()) for i in s.split('\n')])
[(2500.341, 2505.5803, 2510.8197, 2516.0593, 2521.2991), (-0.60960758, -1.3031826, -0.64067196, -1.0230898, -0.20078891)]

But note as zip return a list of tuples you can use map function to convert the result to list :

>>> map(list,zip(*[map(float,i.split()) for i in s.split('\n')]))
[[2500.341, 2505.5803, 2510.8197, 2516.0593, 2521.2991], [-0.60960758, -1.3031826, -0.64067196, -1.0230898, -0.20078891]]

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.