user2624599
user2624599

Reputation: 191

Multiple dtypes in a Numpy array

I have the following data set in a numpy array:

Array 1:

[[a, 1, 20]
 [a, 3, 40]
 [b, 1, 20]
 [b, 2, 40]
 [c, 5, 90]]

Array 2:

[[a, 2]
 [a, 5]]

What I'm trying to accomplish is the following: Array2[0,0]=a, and Array2[0,1]=2 I want to interpolate from the first array to find a,2,30.

To do this I'm using np.where(Array1==item)[0] which looks for 'a', I can't interpolate though because the dtype used to import was a string, not an int.

It's been a while since I've used Numpy so if I'm completely in the weeds please let me know.

Upvotes: 4

Views: 8094

Answers (1)

abarnert
abarnert

Reputation: 365627

I'm not entirely clear on what you're trying to do, but it sounds like you want to specify an aggregate dtype.

This is explained in detail in the dtype docs.

For example, here's a way to specify that each row has a 1-character string and a 64-bit native float (when you don't care what the field names are):

dt = np.dtype('U1, f8')

There are of course other ways to write this; read the full page for details.

And, assuming you've read this in with loadtxt, the docs there have a nice example of using such a dtype. For example:

>>> s2 = 'a 2\na 5\n'
>>> i2 = io.StringIO(s2)
>>> a2 = np.loadtxt(i2, 'U1, i4')
>>> a2
array([('a', 2), ('a', 5)],
      dtype=[('f0', '<U1'), ('f1', '<i4')])

Upvotes: 1

Related Questions