【发布时间】:2016-11-29 20:00:21
【问题描述】:
我想做的事:
将表示百分比 xx% 的字符串转换为 0 到 1 之间的浮点数
我的代码:
#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)
我的问题:
在一般情况下,以 % 为单位的百分比将打印为 nan。由于故障 dtype 是浮点数,因此无法转换百分比。因此,我尝试了转换器方法。
但是,当我运行代码时,出现错误:
convertfunc = lambda x: float(x.strip("%"))/100 # remove % and return the value in float (between 0 and 1)
TypeError: a bytes-like object is required, not 'str'
有人知道这里有什么问题吗? (我用的是python3.5)
感谢您的任何回答。
【问题讨论】:
标签: python numpy python-3.5 converters