Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy csv import problem

Tags:

python

csv

numpy

I am having some difficulty with importing data from a .csv file. I am simply trying to import the data and print the max value. Here is my code:

>>> x, y = numpy.loadtxt('data.csv', delimiter=',', usecols=(4,5), unpack=True)
>>> print 'max =', max(x)

When I enter the above code, I get the following error message:

TypeError: 'numpy.float64' object is not iterable

I tried to change the data type using the dtype=int argument, but it threw the same error. Does anyone have any idea what could be the problem? Thanks in advance for your help!

like image 758
drbunsen Avatar asked Feb 15 '26 21:02

drbunsen


1 Answers

The output of loadtxt() is unfortunately a bit inconistent: If there is only one line in your file, x and y will be scalars, but for more than one line, they will be arrays. The Python built-in max() only works for iterables, so it only works in the latter case.

Using the Python built-in max() function instead of numpy.max() is inefficient for NumPy arrays anyway. So a solution is to use

print x.max()

or

print numpy.max(x)

in the second line.

like image 105
Sven Marnach Avatar answered Feb 18 '26 11:02

Sven Marnach



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!