简体   繁体   中英

Manipulating a list of numbers into columns or separate lists for plotting in Python

I'm pretty new to Python, so I'm sorry if this one is quite easy. (it seems easy to me, but I'm struggling...)

I have a list of numbers kicked back from a Keithley SMU 2400 from an IV sweep I've done, and there resulting list is ordered like the following:

[v0, c0, t0, v1, c1, t1, v2, c2, t2, ...]

The list appears to be a list of numbers (not a list of ascii values thanks to PyVisa's query_ascii_values command).

How can I parse these into either columns of numbers (for output in csv or similar) or three separate lists for plotting in matplotlib.

The output I'd love would be similar to this in the end:

volts = [v0, v1, v2, v3...]
currents = [c0, c1, c2, c3...]
times = [t0, t1, t2, t3...]

that should enable easier plotting in matplotlib (or outputting into a csv text file).

Please note that my v0, v1 etc., are just my names for them, they are numbers currently.

I would have attempted this in Matlab similar to this:

volts = mydata(1:3:length(mydata));

(calling the index by counting every third item from 1)

Thanks for your thoughts and help! Also- are there any good resources for simple data munging like this that I should get a copy of?

Simply slicing works. Thus, with A as the input list, we would have -

volts, currents, times = A[::3], A[1::3], A[2::3]

If you want to keep it a list, then Divakar's solution works well. However, if you will be doing analysis and plotting later, you really want to be using a numpy array, and this makes what you want to do easier still.

To get it into a numpy array, you can do:

>>> import numpy as np
>>> 
>>> mydata = np.array(mydata)

To get it into individual variables, you can just do:

>>> volts, currents, times = mydata.reshape(-1,3).T

This reshapes into a Nx3 array, then transposes it to a 3xN array, then puts each row in a separate variable. One advantage of this is it is very fast, since only one array is ever created, unlike the list approach where 4 lists need to be created (especially if you put the data directly into a numpy array).

You can also use the identical approach Divakar used with lists, again avoiding creating additional lists.

That being said, I would strongly suggest you look into pandas. It will make keeping track of data like this much easier. You can label the columns of an array with informative names, meaning you don't need to split data like this into three variables to keep track of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM