3

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!

3
  • Which line gives the error? Commented Jun 5, 2011 at 14:43
  • 2
    If your file only contains a single line, loadtxt() unfortunately returns a scalar for x and y instead of an array with a single entry. Is there only one line in your file? Commented Jun 5, 2011 at 14:44
  • The data.csv file contains one row of data with numerous columns. Is the solution to add more rows to the 'data.csv` file? Commented Jun 5, 2011 at 14:56

1 Answer 1

4

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.

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

1 Comment

Thank you! This was very helpful. I appreciate you taking the time to explain things so clearly.

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.