我有以下数组" class_id"
array([[array(['2'],
dtype='<U1')],
[array(['3'],
dtype='<U1')],
[array(['2'],
dtype='<U1')],
...,
[array(['2'],
dtype='<U1')],
[array(['2'],
dtype='<U1')],
[array(['2'],
dtype='<U1')]], dtype=object)
当我使用该功能时:
class_id.astype(int)
我收到以下错误:
ValueError: setting an array element with a sequence.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-124-3ad39bf87e7d> in <module>()
----> 1 class_id.astype(int)
ValueError: setting an array element with a sequence.
我想获得以下数组:
array([[1],
[2],
[1],
...,
[1],
[1],
[1]])
我应该使用哪种功能?
答案 0 :(得分:1)
您有一系列数组列表,您需要删除一个图层/维度以获得所需的输出;你可以试试这个:
import numpy as np
np.array([s[0].astype(int) for s in class_id])
#array([[2],
# [3],
# [2],
# [2],
# [2],
# [2]])
class_id = array([[array(['2'],
dtype='<U1')],
[array(['3'],
dtype='<U1')],
[array(['2'],
dtype='<U1')],
[array(['2'],
dtype='<U1')],
[array(['2'],
dtype='<U1')],
[array(['2'],
dtype='<U1')]], dtype=object)
答案 1 :(得分:0)
要重新创建数组,我必须使用:
array = np.array
In [460]: alist = [[array(['2'],
...: dtype='<U1')],
...: [array(['3'],
...: dtype='<U1')],
...: [array(['2'],
...: dtype='<U1')],
...: [array(['2'],
...: dtype='<U1')],
...: [array(['2'],
...: dtype='<U1')],
...: [array(['2'],
...: dtype='<U1')]]
In [461]: arr = np.zeros((6,1), dtype=object)
In [462]: arr[:,0] = alist
In [463]: arr
Out[463]:
array([[[array(['2'],
dtype='<U1')]],
[[array(['3'],
dtype='<U1')]],
[[array(['2'],
dtype='<U1')]],
[[array(['2'],
dtype='<U1')]],
[[array(['2'],
dtype='<U1')]],
[[array(['2'],
dtype='<U1')]]], dtype=object)
简单的复制n粘贴剥离内部数组定义:
array([[['2']], # (6,1,1) shape
[['3']],
...
[['2']]], dtype=object)
使用arr[:,0]
删除一级[],我可以使用连接加入数组,并通过一次调用U1
轻松将int
数组转换为astype
。
In [464]: np.concatenate(arr[:,0])
Out[464]:
array([['2'],
['3'],
['2'],
['2'],
['2'],
['2']],
dtype='<U1')
In [465]: np.concatenate(arr[:,0]).astype(int)
Out[465]:
array([[2],
[3],
[2],
[2],
[2],
[2]])