[Numpy-discussion] using loadtxt to load a text file in to a numpy array

Randewijk, PJ, Dr <pjrandew@sun.ac.za> pjrandew at sun.ac.za
Sat Jan 18 05:40:28 EST 2014




Gestuur vanaf my Samsung S3 Mini



-------- Original message --------
From: josef.pktd at gmail.com
Date: 18/01/2014 04:16 (GMT+02:00)
To: Discussion of Numerical Python <numpy-discussion at scipy.org>
Subject: Re: [Numpy-discussion] using loadtxt to load a text file in to a numpy array


It looks like both recfromtxt and loadtxt are flexible enough to
handle string/bytes en/decoding, - with a bit of work and using enough
information

>>> dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<U9')]

>>> data = numpy.recfromtxt(open('Õscar_3.txt',"rb"), dtype=dtype, delimiter=',',converters={3:lambda x: x.decode('utf8')})
>>> data['f3'] == 'Õscar'
array([False, False, False,  True], dtype=bool)
>>> data
rec.array([(1, 2, 3, 'hello'), (5, 6, 7, 'Õscarscar'), (15, 2, 3, 'hello'),
       (20, 2, 3, 'Õscar')],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<U9')])


>>> data = numpy.loadtxt(open('Õscar_3.txt',"rb"), dtype=dtype, delimiter=',',converters={3:lambda x: x.decode('utf8')})
>>> data
array([(1, 2, 3, 'hello'), (5, 6, 7, 'Õscarscar'), (15, 2, 3, 'hello'),
       (20, 2, 3, 'Õscar')],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<U9')])
>>>

Josef
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion at scipy.org
http://mail.scipy.org/mailman/listinfo/numpy-discussion

________________________________

E-pos vrywaringsklousule Hierdie e-pos mag vertroulike inligting bevat en mag regtens geprivilegeerd wees en is slegs bedoel vir die persoon aan wie dit geadresseer is. Indien u nie die bedoelde ontvanger is nie, word u hiermee in kennis gestel dat u hierdie dokument geensins mag gebruik, versprei of kopieer nie. Stel ook asseblief die sender onmiddellik per telefoon in kennis en vee die e-pos uit. Die Universiteit aanvaar nie aanspreeklikheid vir enige skade, verlies of uitgawe wat voortspruit uit hierdie e-pos en/of die oopmaak van enige lêers aangeheg by hierdie e-pos nie. E-mail disclaimer This e-mail may contain confidential information and may be legally privileged and is intended only for the person to whom it is addressed. If you are not the intended recipient, you are notified that you may not use, distribute or copy this document in any manner whatsoever. Kindly also notify the sender immediately by telephone, and delete the e-mail. The University does not accept liability for any damage, loss or expense arising from this e-mail and/or accessing any files attached to this e-mail.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140118/783d8252/attachment.html>


More information about the NumPy-Discussion mailing list