Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting data file columns into separate arrays in Python

Tags:

python

I'm new to python and have been trying to figure this out all day. I have a data file laid out as below,

time    I(R_stkb)

Step Information: Temp=0  (Run: 1/11)

0.000000000000000e+000  0.000000e+000

9.999999960041972e-012  8.924141e-012

1.999999992008394e-011  9.623148e-012

3.999999984016789e-011  6.154220e-012

(Note: No empty line between the each data line.)

I want to plot the data using matplotlib functions, so I'll need the two separate columns in arrays.

I currently have

def plotdata():

Xvals=[], Yvals=[]
i = open(file,'r')

for line in i:
    Xvals,Yvals = line.split(' ', 1)

print Xvals,Yvals

But obviously its completely wrong. Can anyone give me a simple answer to this, and with an explanation of what exactly the lines mean would be helpful. Cheers.

Edit: The first two lines repeat throughout the file.

like image 880
T May Avatar asked Mar 07 '26 08:03

T May


1 Answers

This is a job for the * operator on the zip method.

>>> asdf
[[1, 2], [3, 4], [5, 6]]


>>> zip(*asdf)
[(1, 3, 5), (2, 4, 6)]

So in the context of your data it might be something like:

handle = open(file,'r')
lines = [line.split() for line in handle if line[:4] not in ('time', 'Step')]
Xvals, Yvals = zip(*lines)

or if your really need to be able to mutate the data afterwards you could just call the list constructor on each tuple:

Xvals, Yvals = [list(block) for block in zip(*lines)]
like image 127
machine yearning Avatar answered Mar 09 '26 21:03

machine yearning



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!