How to make the converters keyword of genfromtxt (numpy) work in Python 3? -
from numpy user guide take following example uses converters keyword format data
from io import bytesio convertfunc = lambda x: float(x.strip("%"))/100 data = "1, 2.3%, 45.\n6, 78.9%, 0." names = ('i', 'p', 'n') = np.genfromtxt(bytesio(data.encode()), delimiter = ',', names = names, converters = {1 : convertfunc}) print(a) however, not work in python 3. error message
traceback (most recent call last): file "/users/macbookpro/documents/workspace/python3/learnnumpy/importingdata.py", line 46, in <module> = np.genfromtxt(bytesio(data.encode()), delimiter = ',', names = names, converters = {1 : convertfunc}) file "/users/macbookpro/anaconda/lib/python3.4/site-packages/numpy/lib/npyio.py", line 1708, in genfromtxt (i, conv) in enumerate(converters)])) file "/users/macbookpro/anaconda/lib/python3.4/site-packages/numpy/lib/npyio.py", line 1708, in <listcomp> (i, conv) in enumerate(converters)])) file "/users/macbookpro/anaconda/lib/python3.4/site-packages/numpy/lib/npyio.py", line 1707, in <listcomp> zip(*[[conv._loose_call(_r) _r in map(itemgetter(i), rows)] file "/users/macbookpro/anaconda/lib/python3.4/site-packages/numpy/lib/_iotools.py", line 668, in _loose_call return self.func(value) file "/users/macbookpro/documents/workspace/python3/learnnumpy/importingdata.py", line 43, in <lambda> convertfunc = lambda x: float(x.strip("%"))/100 typeerror: 'str' not support buffer interface how make work , matter of fact, why fail exactly?
you need change string literal in convertfunc byte-string changing "%" b"%" or "%".encode()
the reason in python 3 strings unicode default, whereas in python 2 strings bytes default.
Comments
Post a Comment