gpt4 book ai didi

python - 使用 Python 字典时出现 "ValueError: could not convert string to float:"

转载 作者:行者123 更新时间:2023-12-01 01:07:52 25 4
gpt4 key购买 nike

我正在尝试将字符串复制到由 float 组成的字典中。我尝试在复制之前将字典值更改为字符串。它不起作用。我将问题分解为以下代码:

tst_dict = {}

tst_dict['name'] = np.zeros((2,3))

tst_dict['name'][0,0] = str(tst_dict['name'][0,0])
tst_dict['name'][0,0] = 'Hase'

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

感谢您的帮助。

最佳答案

使用dtype=object ,你会得到一个 python 对象引用数组。这样你就可以拥有Python字符串的所有行为:

import numpy as np

tst_dict = {}
tst_dict['name'] = np.zeros((2,3), dtype=object)
tst_dict['name'][0,0] = str(tst_dict['name'][0,0])
tst_dict['name'][0,0] = 'Hase'

print(tst_dict)

输出:

{'name': array([['Hase', 0, 0],
[0, 0, 0]], dtype=object)}

编辑:

使用dtype='<U1'求单charstr :

import numpy as np

tst_dict = {}
tst_dict['name'] = np.zeros((2,3), dtype='<U1')
tst_dict['name'][0,0] = str(tst_dict['name'][0,0])
tst_dict['name'][0,0] = 'Hase'

print(tst_dict)

输出:

{'name': array([['H', '', ''],
['', '', '']], dtype='<U1')}

关于python - 使用 Python 字典时出现 "ValueError: could not convert string to float:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com