Python 如何连接2个数组:1个数组包含字符串,另一个数组包含int64

Python 如何连接2个数组:1个数组包含字符串,另一个数组包含int64,python,arrays,numpy,Python,Arrays,Numpy,我很难用numpy连接两个数组。 其中一个数组有文本(string),另一个数组有数字(int64) 我该怎么做 使用np.concatenate()将所有值设置为字符串,并且需要两者 我正在运行for循环来确定RandomForestClassifier的超参数。。。当循环转到数字时,给出一个错误,因为需要数字并获取字符串'1'或'2' 我正在使用 np.concatenate((['auto'], np.arange(20, 120, 20)), axis=0, out=None) 得到

我很难用numpy连接两个数组。 其中一个数组有文本(
string
),另一个数组有数字(
int64

我该怎么做

使用
np.concatenate()
将所有值设置为字符串,并且需要两者

我正在运行for循环来确定
RandomForestClassifier
的超参数。。。当循环转到数字时,给出一个错误,因为需要数字并获取字符串
'1'
'2'

我正在使用

np.concatenate((['auto'], np.arange(20, 120, 20)), axis=0, out=None)
得到

array(['auto', '20', '40', '60', '80', '100'], dtype='<U11')

虽然这可能不是最好的解决方案,但它会起作用:

np.asarray(['auto']+list(np.arange(20,120,20)),dtype=object)
结果:

array(['auto',20,40,60,80,100],dtype=object)

问题在于,您正在组合不同的类型,因此您需要告诉numpy,所有对象都可以原样使用,无需转换。

要连接的数组之一应该具有object dtype,以便获得具有object type的最终数组,该数组可以容纳具有异构数据类型的项:

In [7]: np.concatenate((['auto'], np.arange(20, 120, 20).astype(object)), axis=0, out=None)
Out[7]: array(['auto', 20, 40, 60, 80, 100], dtype=object)

如果您想知道Numpy如何确定使用
object
dtype可以读取的数组类型,那么您就失去了使用数字dtype的许多速度和便利性。这样的数组基本上是一个列表。事实上,在等价列表上的迭代速度更快。
In [7]: np.concatenate((['auto'], np.arange(20, 120, 20).astype(object)), axis=0, out=None)
Out[7]: array(['auto', 20, 40, 60, 80, 100], dtype=object)