2

I was curious whether there is a nicer way to do this. I have a csv file with two columns (which is fairly common), for example the 1st column is the time stamp and the second column is the data.

# temp.csv
0., 0.
1., 5.
2., 10.
3., 15.
4., 10.
5., 0.

And then I want to read this temp.csv file:

import numpy as np

my_csv = np.genfromtxt('./temp.csv', delimiter=',')
time = my_csv[:, 0]
data = my_csv[:, 1]

This is entirely fine, but I am just curious whether there is a more elegant way to do this, since this is a fairly common practice.

Thank you!

-Shawn

0

3 Answers 3

5

You can do:

my_csv = np.genfromtxt('./temp.csv', delimiter=',')
time, data = my_csv.transpose()

or the one liner:

time, data = np.genfromtxt('./temp.csv', delimiter=',').transpose()

or another one liner where genfromtxt does the transposition:

time, data = np.genfromtxt('./temp.csv', delimiter=',', unpack=True)

Are they more elegant? That's up to the reader.

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

2 Comments

Thank you! I think this is quite elegant. Warren's answer is great too!
Quick comment for future readers: I am now using time, data = np.genfromtxt('./temp.csv', delimiter=',').T because I think this is the clearest way :)
2

You can use the unpack argument to have genfromtxt return the transpose of the array. Then you can do your assignments like this:

In [3]: time, data = genfromtxt('temp.csv', unpack=True, delimiter=',')

In [4]: time
Out[4]: array([ 0.,  1.,  2.,  3.,  4.,  5.])

In [5]: data
Out[5]: array([  0.,   5.,  10.,  15.,  10.,   0.])

1 Comment

Thank you! I didn't realize that there is a unpack argument. This is actually what I was wondering!
1

Use pandas dataframes if you want nice ways for working with csv type tables.'

http://pandas.pydata.org/pandas-docs/dev/dsintro.html

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.