How to convert a Numpy 2D array with object dtype to a regular 2D array of floats

后端 未结 6 1528
太阳男子
太阳男子 2020-12-09 10:02

As part of broader program I am working on, I ended up with object arrays with strings, 3D coordinates and etc all mixed. I know object arrays might not be very favorite in

6条回答
  •  -上瘾入骨i
    2020-12-09 10:32

    You may want to use structured array, so that when you need to access the names and the values independently you can easily do so. In this example, there are two data points:

    x = zeros(2, dtype=[('name','S10'), ('value','f4',(3,))])
    x[0][0]='item1'
    x[1][0]='item2'
    y1=x['name']
    y2=x['value']
    

    the result:

    >>> y1
    array(['item1', 'item2'], 
          dtype='|S10')
    >>> y2
    array([[ 0.,  0.,  0.],
           [ 0.,  0.,  0.]], dtype=float32)
    

    See more details: http://docs.scipy.org/doc/numpy/user/basics.rec.html

提交回复
热议问题