ValueError:无法将字符串转换为浮点值:“x”

2024-03-28 23:11:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个矩阵image&;convolved。卷积中的某些元素必须替换为字符串“x”。对应于“x”值的索引是那些出现在图像矩阵中的1。 这是我的矩阵

import numpy as np

image = np.array([[0, 1, 0, 1, 0], [0, 0, 0, 1, 1],[0, 0, 0, 0, 0]])

convolved = np.array([[1., 1., 3., 3., 3.],[1., 1., 3., 3., 3.],[0., 0., 1., 2., 2.]])

这是我写的

for m, i in enumerate(image):
    for n, j in enumerate(i):
        if j == 1:
            #print(n,j)
            convolved[m][n] = "x"
print(convolved)

当我运行这个时,我得到以下错误

ValueError: could not convert string to float: 'x'

我想有这个输出

array([[1., 'x', 3., 'x', 3.],
       [1., 1., 3., 'x', 'x'],
       [0., 0., 1., 2., 2.]])

有人能告诉我我做错了什么吗? 谢谢。你知道吗


Tags: 字符串in图像imageimport元素fornp
2条回答

您可以尝试使用pandas

import pandas as pd

image = pd.DataFrame([[0, 1, 0, 1, 0], [0, 0, 0, 1, 1],[0, 0, 0, 0, 0]])

convolved = pd.DataFrame([[1., 1., 3., 3., 3.],[1., 1., 3., 3., 3.],[0., 0., 1., 2., 2.]])

for i in image:
    for j in image[i]:
        if image[i][j] == 1:
            convolved[i][j] = "x"
print(convolved)

你是想给np.数组字符值。您正在混合数据类型。那是行不通的np.数组需要数字类型的数据。 https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html

或者使用一个唯一的数字代替“x”,比如-1,或者将整个数组改为chars,比如numpy.chararray公司. https://docs.scipy.org/doc/numpy/reference/generated/numpy.chararray.html

相关问题 更多 >