python - 重新分配 numpy.array()

标签 python arrays numpy numpy-ndarray

在下面的代码中,我可以轻松地减少数组['a','b','a','c','b','b','c','a'] 转换为二进制数组 [0 1 0 1 1 1 1 0],以便 'a' -> 0'b','c ' -> 1。如何将其转换为三元数组,以便 'a' -> 0'b' -> 1'c' -> 2 code>,而不使用 forif-else?谢谢。

import numpy as np
x = np.array(['a', 'b', 'a', 'c', 'b', 'b', 'c', 'a'])
y = np.where(x=='a', 0, 1)
print(y)

最佳答案

通过这样做:

np.where(x == 'a', 0, (np.where(x == 'b', 1, 2)))

请注意,这会将所有既不是“a”也不是“b”的字符更改为 2。我假设您只有一个包含 a、b 和 c 的数组。

关于python - 重新分配 numpy.array(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63310069/

相关文章:

python - 如何同时使用字典和数组的 for 循环

python - 使用 Apache NiFi 解密基于 RSA 的加密

python - 在 MacOS 上使用 pyuno 进行文件转换

python - 如何在 Python 中获取 SQLite 结果/错误代码

arrays - 使用 2 个单独的列定义数组

python - 将 NumPy 数组矢量化重新标记为连续数字并检索回来

python - 我如何将音量添加到 pyalsaaudio 中的 current_volume 列表?

c++ - 如何格式化数组并输出?

javascript - 选择多个数组元素javascript

python - 向量化 numpy 对于子数组是唯一的