thegreatt
thegreatt

Reputation: 1419

Error using NumPy.fromiter() with MySQL query results

I have a very simple query, and I'm trying to convert it into a NumPy array using the fromiter() function. However, I can't figure out why it's not working, or what the error below means. Any ideas?

import numpy as np

c.execute("SELECT video_id FROM video")
results = c.fetchall()
D = np.fromiter(results, dtype=float, count=-1) 

ERROR: ValueError: setting an array element with a sequence.

Upvotes: 0

Views: 996

Answers (3)

agf
agf

Reputation: 176820

import numpy as np
from itertools import chain

c.execute("SELECT video_id FROM video")
results = c.fetchall()
D = np.fromiter(chain.from_iterable(results), dtype=float, count=-1) 

This should extract the values from the tuples in results.

Upvotes: 2

Keith
Keith

Reputation: 43024

As before, results returns tuples, so you will have to pull the value out of the tuple using itertools.imap, or your own iterable adapter.

results = itertools.imap(lambda t: t[0], results)

But I'm just guessing the index since I don't know what you are querying.

Upvotes: 2

Colin Valliant
Colin Valliant

Reputation: 1929

I'm not expert with MySQL, but it looks like results is ending up as a list where each element is a sequence, like results = [(foo, bar), (baz, bid)], and those items aren't valid numpy array values.

Make sure that each element of results is actually a float, and not, say, a float in a tuple.

Upvotes: 0

Related Questions