【问题标题】:Numpy I/O: convert % percentage to float between 0 and 1Numpy I/O:将百分比转换为 0 到 1 之间的浮点数
【发布时间】: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


    【解决方案1】:

    您不能将 bytes-like 对象与 str 对象即 '%' 分开。将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'>
    

    【讨论】:

    • 非常感谢。这确实回答了我的问题。
    猜你喜欢
    • 2016-04-05
    • 2023-04-05
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2020-05-14
    • 2019-07-19
    相关资源
    最近更新 更多