【问题标题】:How do I do to concatenate 2 arrays: 1 array contains string and the other array contains int64如何连接 2 个数组:1 个数组包含字符串,另一个数组包含 int64
【发布时间】:2019-04-14 22:14:34
【问题描述】:

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

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

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

    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?

    【讨论】:

    • 使用object dtype,您会大大降低使用数字dtype 的速度和便利性。这样的数组基本上是一个列表。事实上,对等价列表的迭代速度更快。
    【解决方案2】:

    虽然可能不是最好的解决方案,但这会奏效:

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

    结果:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-06
      • 2013-11-26
      • 2019-09-03
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多