【问题标题】:Replace an int with a string in a numpy array用 numpy 数组中的字符串替换 int
【发布时间】:2020-07-28 13:05:21
【问题描述】:

我有一个numpy数组如下:

board = np.arange(9).reshape(3, 3)

我想替换数组中的一个值,例如:

board[1, 2] = 'x'.

但据我了解,我不能这样做,因为数组是 int 类型,而我试图用字符串替换它。当我运行它时,我得到了错误:

ValueError: int() 以 10 为底的无效文字:'x'

我尝试将数组的 dtype 设置为 str:

board = np.arange(9, dtype=str).reshape(3, 3)

但这给了我错误:

ValueError:数据类型没有填充功能。

谢谢

【问题讨论】:

  • 初始化后尝试将int数组转换为字符串数组,如下:np.arange(9).astype(np.str).reshape(3, 3).

标签: python-3.x numpy


【解决方案1】:

numpy 中,任何非数字dtype 的类型都是object

这将起作用:

board = np.arange(9, dtype=object).reshape(3, 3)
board[1, 2] = 'x'

干杯。

【讨论】:

    猜你喜欢
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 2012-04-26
    • 1970-01-01
    相关资源
    最近更新 更多