简体   繁体   中英

Use numpy to read a two-column csv file

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

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.

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.])

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

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

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