[Tutor] Change datatype for specific columns in an 2D array & computing the mean

Albert-Jan Roskam sjeik_appie at hotmail.com
Sun Jan 24 15:35:36 EST 2016


> To: tutor at python.org
> From: __peter__ at web.de
> Date: Sun, 24 Jan 2016 11:22:19 +0100
> Subject: Re: [Tutor] Change datatype for specific columns in an 2D array & computing the mean
<snip>
 
> How do you want to convert the second and third column to int? Are A4 and B2 
> hex numbers? Then try
> 
> $ cat esawi.csv 
> 19,A4,B2,2
> 19,A5,B1,12
> $ python3
> Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import numpy
> >>> def fromhex(s):
> ...     return int(s, 16)
> ... 
> >>> numpy.genfromtxt("esawi.csv", delimiter=",", converters={1:fromhex, 
> 2:fromhex})
> array([(19.0, 164, 178, 2.0), (19.0, 165, 177, 12.0)], 
>       dtype=[('f0', '<f8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<f8')])

Wow what a cool trick!! I never knew about 'converters'. And (probably not surprisingly) pandas.read_csv has it too:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
 
 
 
 		 	   		  


More information about the Tutor mailing list