将表示百分比xx%的字符串转换为0到1之间的浮点数
<div name="div12Item" id="div12Item">
new content
<ul id="sortable" >
<li >Item 1</li>
<li >Item 2</li>
<li >Item 3</li>
</ul>
</div>
在一般情况下,百分比(%)将打印为nan。由于故障dtype为float,因此无法转换百分比%。因此,我尝试了转换器方法。
但是,当我运行代码时,会发生错误:
#a. general case
data = "1, 2.3%, 45.\n6, 78.9%, 0"
names = ("i", "p", "n")
a = np.genfromtxt(io.BytesIO(data.encode()), names = names, delimiter = ",")
print (a) # returns [(1.0, nan, 45.0) (6.0, nan, 0.0)]
print (a.dtype) # reason: default dtype is float, cannot convert 2.3%, 78.9%
#b. converter case
convertfunc = lambda x: float(x.strip("%"))/100 # remove % and return the value in float (between 0 and 1)
b = np.genfromtxt(io.BytesIO(data.encode()), names = names, delimiter = ",", converters = {1:convertfunc}) # use indices for 2nd column as key and do the conversion
print (b)
print (b.dtype)
有人知道这里有什么问题吗? (我使用的是python3.5)
感谢您的回答。
答案 0 :(得分:1)
您无法使用str
对象viz '%'
拆分类似字节的对象。将b
附加到 strip 字符串的开头,使其成为字节对象。
convertfunc = lambda x: float(x.strip(b"%"))/100
# ^
b = np.genfromtxt(io.BytesIO(data.encode()), names = names, delimiter = ",", converters = {1:convertfunc})
print(b)
# array([(1.0, 0.023, 45.0), (6.0, 0.789, 0.0)],
# dtype=[('i', '<f8'), ('p', '<f8'), ('n', '<f8')])
具有前导b
的此类对象属于bytes
类:
>>> type('%')
<class 'str'>
>>> type(b'%')
<class 'bytes'>