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

时间:2019-04-14 14:03:22

标签: python arrays numpy

我很难尝试使用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')

但是,我需要

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

2 个答案:

答案 0 :(得分:2)

要连接的数组之一应具有对象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)

如果您想知道Numpy如何确定数组类型,可以阅读How does numpy determin the object-array's dtype and what it means?

答案 1 :(得分:0)

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

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

结果:

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

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