gpt4 book ai didi

python - 我们如何将字符串转换为 float ?

转载 作者:行者123 更新时间:2023-12-01 00:56:13 24 4
gpt4 key购买 nike

嗨,我正在尝试在 jupyter 笔记本中执行一个由 txt 文件组成的单元格,我做了这样的事情:

dataset = numpy.loadtxt("C:/Users/jayjay/learning/try.txt", delimiter=",", skiprows=1)
# split into input (X) and output (Y) variables
X=dataset[:100,2:4]
Y=dataset[:100,4]

当我尝试运行此程序时,出现此错误:

ValueError                                Traceback (most recent call last)
<ipython-input-64-d2d2260af43e> in <module>
----> 1 dataset = numpy.loadtxt("C:/Users/jayjay/learning/try.txt", delimiter=",", skiprows=1)
2 # split into input (X) and output (Y) variables
3 X=dataset[:100,2:4]
4 Y=dataset[:100,4]


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

我在 try.txt 中有一个与此类似的数据:

135,10,125,10,1
230,16,214,19,not 1
226,16,210,19,1
231,16,215,19,not 1
205,16,189,17,not 1

如何解决这个错误?我是一个自学新手。谁能帮我解决这个问题吗?

最佳答案

很高兴您提供了文件示例:

In [1]: txt="""135,10,125,10,1 
...: 230,16,214,19,not 1
...: 226,16,210,19,1
...: 231,16,215,19,not 1
...: 205,16,189,17,not 1"""

loadtxt 接受字符串列表来代替文件:

In [2]: np.loadtxt(txt.splitlines(),delimiter=',')                           
...
ValueError: could not convert string to float: 'not 1'

它尝试返回一个 float 组,但 not 1 字符串出现问题:

genfromtxt 类似,但在可以创建 float 时给出 nan:

In [3]: np.genfromtxt(txt.splitlines(),delimiter=',')                        
Out[3]:
array([[135., 10., 125., 10., 1.],
[230., 16., 214., 19., nan],
[226., 16., 210., 19., 1.],
[231., 16., 215., 19., nan],
[205., 16., 189., 17., nan]])

您可以跳过问题列:

In [4]: np.loadtxt(txt.splitlines(),delimiter=',', usecols=[0,1,2,3])        
Out[4]:
array([[135., 10., 125., 10.],
[230., 16., 214., 19.],
[226., 16., 210., 19.],
[231., 16., 215., 19.],
[205., 16., 189., 17.]])

或者因为您无论如何都要将数组拆分为两个数组:

In [8]: np.genfromtxt(txt.splitlines(),delimiter=',', usecols=[0,1,2,3], dtype=int)                                                               
Out[8]:
array([[135, 10, 125, 10],
[230, 16, 214, 19],
[226, 16, 210, 19],
[231, 16, 215, 19],
[205, 16, 189, 17]])
In [9]: np.genfromtxt(txt.splitlines(),delimiter=',', usecols=[4], dtype=None, encoding=None)
Out[9]: array(['1', 'not 1', '1', 'not 1', 'not 1'], dtype='<U5')

dtype=None 让它为每列选择适当的数据类型。

In [10]: np.genfromtxt(txt.splitlines(),delimiter=',', dtype=None, encoding=N
...: one)
Out[10]:
array([(135, 10, 125, 10, '1'), (230, 16, 214, 19, 'not 1'),
(226, 16, 210, 19, '1'), (231, 16, 215, 19, 'not 1'),
(205, 16, 189, 17, 'not 1')],
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<U5')])

这是一个结构化数组,每列都有一个字段。并具有更高级的数据类型规范:

In [13]: np.genfromtxt(txt.splitlines(),delimiter=',', dtype='4i,U5', encoding=None)                                                             
Out[13]:
array([([135, 10, 125, 10], '1'), ([230, 16, 214, 19], 'not 1'),
([226, 16, 210, 19], '1'), ([231, 16, 215, 19], 'not 1'),
([205, 16, 189, 17], 'not 1')],
dtype=[('f0', '<i4', (4,)), ('f1', '<U5')])
In [14]: _['f0']
Out[14]:
array([[135, 10, 125, 10],
[230, 16, 214, 19],
[226, 16, 210, 19],
[231, 16, 215, 19],
[205, 16, 189, 17]], dtype=int32)
In [15]: __['f1']
Out[15]: array(['1', 'not 1', '1', 'not 1', 'not 1'], dtype='<U5')

到目前为止,我还没有尝试解析或转换那些“not 1”字符串。我们可以构造一个转换器,将其转换为数字,例如 0。

如果我定义一个转换器函数,例如:

def foo(astr):
if astr==b'not 1':
astr = b'0'
return int(astr)

In [31]: np.genfromtxt(txt.splitlines(),delimiter=',', converters={4:foo}, dtype=int)
Out[31]:
array([[135, 10, 125, 10, 1],
[230, 16, 214, 19, 0],
[226, 16, 210, 19, 1],
[231, 16, 215, 19, 0],
[205, 16, 189, 17, 0]])

或者如果转换器返回 float :

def foo(astr):
if astr==b'not 1':
astr = b'0'
return float(astr)
In [39]: np.genfromtxt(txt.splitlines(),delimiter=',', converters={4:foo})
Out[39]:
array([[135., 10., 125., 10., 1.],
[230., 16., 214., 19., 0.],
[226., 16., 210., 19., 1.],
[231., 16., 215., 19., 0.],
[205., 16., 189., 17., 0.]])

关于python - 我们如何将字符串转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237485/

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