np 数组转为普通数组_如何将列表的np数组转换为np数组

latest updated:

>>> a = np.array(["0,1", "2,3", "4,5"])

>>> a

array(['0,1', '2,3', '4,5'], dtype='|S3')

>>> b = np.core.defchararray.split(a, sep=',')

>>> b

array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)

>>> c = np.array(b).astype(float)

Traceback (most recent call last):

File "", line 1, in

ValueError: setting an array element with a sequence.

old:

I have a np array like this:

array([[list(['3', '6']), list(['2', '1'])],

[list(['0', '7']), list(['1', ' 9'])]], dtype=object)

I want to convert it to a np array of string like this:

array([[['3', '6'], ['2', '1']],

[['0', '7'], ['1', ' 9']]], dtype=object)

so that I can use astype("float32") to directly convert it to a float array.

any idea?

old update:

thx for your suggestions but I cannot find the difference.

解决方案

I was wondering how you got the array of lists. That usually takes some trickery.

In [2]: >>> a = np.array(["0,1", "2,3", "4,5"])

...: >>> b = np.core.defchararray.split(a, sep=',')

...:

In [4]: b

Out[4]: array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)

Simply calling array again doesn't change things:

In [5]: np.array(b)

Out[5]: array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)

stack works - it views b as a list of elements, in this case lists, and joins them on a new axis

In [6]: np.stack(b)

Out[6]:

array([['0', '1'],

['2', '3'],

['4', '5']], dtype='

In [7]: np.stack(b).astype(float)

Out[7]:

array([[0., 1.],

[2., 3.],

[4., 5.]])

But your 'old' case was a 2d array of lists. This stack trick does not work, at least not directly.

In [8]: a = np.array(["0,1", "2,3", "4,5","6,7"]).reshape(2,2)

In [9]: b = np.core.defchararray.split(a, sep=',')

In [11]: np.stack(b)

Out[11]:

array([[list(['0', '1']), list(['2', '3'])],

[list(['4', '5']), list(['6', '7'])]], dtype=object)

In [12]: np.stack(b.ravel())

Out[12]:

array([['0', '1'],

['2', '3'],

['4', '5'],

['6', '7']], dtype='

or

In [13]: np.array(b.tolist())

Out[13]:

array([[['0', '1'],

['2', '3']],

[['4', '5'],

['6', '7']]], dtype='

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值