Multiple dtypes in a Numpy array

巧了我就是萌 提交于 2021-02-07 19:40:19

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/27325781/multiple-dtypes-in-a-numpy-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!