python - 我们如何将字符串转换为浮点数?
问题描述
嗨,我试图在 jupyter notebook 中执行一个包含 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'
它试图返回一个浮点数组,但not 1
字符串会出现问题:
genfromtxt
类似,但给出了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
让它为每一列选择适当的 dtype。
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')])
这是一个结构化数组,field
每列都有一个。并具有更高级的 dtype 规范:
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')
到目前为止,我还没有尝试解析或转换那些“非 1”字符串。我们可以构造一个converter
将其转换为数字的 a,例如 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]])
或者如果转换器返回一个浮点数:
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.]])
推荐阅读
- jquery - 选择选项不会触发 Jquery
- c# - 找不到名称为 Pomelo.EntityFrameworkCore.MySql 的提供程序程序集
- eclipse - 自定义现有菜单项
- c++ - 使用 Cmake 编译 QtGstreamer 时出错,Mingw32 编译器附带 QT 5.12.3
- python - 使用方法从继承自 selenium 类的 python appium 类中查找元素时,Appium 未找到元素
- c# - Combobox does not showing added items (with if condition)
- mysql - varchar 列上的 MySQL first_value 返回格式错误的记录
- javascript - How can I request the default favicon using Node?
- javascript - nuxt - creating child routes for mandatory param route
- robots.txt - 如何保护来自机器人的机密目录?