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

2024-04-27 10:45:59 发布

您现在位置:Python中文网/ 问答频道 /正文

最新更新:

>>> 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 "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.

旧:

我有一个这样的np数组:

^{pr2}$

我想把它转换成一个np字符串数组,如下所示:

array([[['3', '6'], ['2', '1']],
       [['0', '7'], ['1', ' 9']]], dtype=object)

所以我可以使用astype(“float32”)直接将其转换为float数组。在

有什么想法吗?在

旧更新:

enter image description here

谢谢你的建议,但我找不到区别。在


Tags: coremostobjects3np数组floatarray
2条回答

我想知道你是怎么得到这一系列名单的。这通常需要一些诡计。在

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)

再次调用数组并不能改变事情:

^{pr2}$

stack起作用-它将b视为一个元素列表,在本例中是列表,并将它们连接到一个新的轴上

In [6]: np.stack(b)
Out[6]: 
array([['0', '1'],
       ['2', '3'],
       ['4', '5']], dtype='<U1')
In [7]: np.stack(b).astype(float)
Out[7]: 
array([[0., 1.],
       [2., 3.],
       [4., 5.]])

但你的“旧”案例是一个二维列表数组。这个堆栈技巧不起作用,至少不直接起作用。在

^{4}$

或者

In [13]: np.array(b.tolist())
Out[13]: 
array([[['0', '1'],
        ['2', '3']],

       [['4', '5'],
        ['6', '7']]], dtype='<U1')

评论中的建议对我很有效。在

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

res = np.array(arr).astype(float)

print(res, res.dtype, res.shape)

# [[ 0.  1.]
#  [ 2.  3.]
#  [ 4.  5.]] float64 (3, 2)

相关问题 更多 >