python - 用 NumPy 中的列表元素替换数组元素

标签 python numpy matrix

我有一个 NumPy 数组,我将它转换成一个名为 string_matrix 的矩阵,其中每个元素都是一个字符串。 现在我想将 string_matrix 中的每个元素转换为字母。矩阵中的数字是列表 alp 的索引。 所以我想要这个输出:string_matrix = [['l' 'i' 'a']['a' 'f' 'b']['u' 'e' 'k']]

alp = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",""]
matrix = numpy.array([[11, 8, 0],[0, 5, 1],[20, 4, 10]])
string_matrix = numpy.array(["%.f" % v for v in matrix.reshape(matrix.size)])
string_matrix = string_matrix.reshape(matrix.shape)

最佳答案

您可以使用您的矩阵索引到alp列表,您需要先将alp设为一个numpy数组:

numpy.array(alp)[matrix]

输出:

array([['l', 'i', 'a'],
       ['a', 'f', 'b'],
       ['u', 'e', 'k']], dtype='<U1')

这使用了 numpy 的高级索引。您可以找到更多详细信息 here如果您想阅读它。

关于python - 用 NumPy 中的列表元素替换数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460852/

相关文章:

python - 函数装饰器指定 def 的前两行?

python - 如果使用 Pandas 在所有列中包含字符串,则对数据框进行样式设置

python - Cython:为什么 NumPy 数组需要类型转换为对象?

numpy - 两台计算机上相同的numpy均值计算结果不同

python - 在无堆栈 Python 中,您可以通过 channel 发送 channel 吗?

python - 当工作人员数量增加并且 numpy 生成大型数组时,Keras 使用较少的 CPU

python - 矩阵运算后得到输出

matlab - 如何对矩阵中每一行的每 n 列进行平均?

matrix - 高效地从向量中提取任意切片

python - 值错误: could not convert string to float:While loading data from sql server to Predict()