如何将列表的np数组转换为np数组 [英] how to convert a np array of lists to a np array
问题描述
最新更新:
>>> 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数组:
I have a np array like this:
array([[list(['3', '6']), list(['2', '1'])],
[list(['0', '7']), list(['1', ' 9'])]], dtype=object)
我想将其转换为如下所示的字符串的np数组:
I want to convert it to a np array of string like this:
array([[['3', '6'], ['2', '1']],
[['0', '7'], ['1', ' 9']]], dtype=object)
以便我可以使用astype("float32")将其直接转换为float数组.
so that I can use astype("float32") to directly convert it to a float array.
有什么主意吗?
旧更新:
谢谢您的建议,但我找不到区别.
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
起作用-将b
视为元素列表(在本例中为列表),并将它们连接到新轴上
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='<U1')
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='<U1')
或
In [13]: np.array(b.tolist())
Out[13]:
array([[['0', '1'],
['2', '3']],
[['4', '5'],
['6', '7']]], dtype='<U1')
这篇关于如何将列表的np数组转换为np数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!