Converting list of lists to numpy array with multiple data types -
i have list of lists i've read file. each of inner lists 6 elements in length, , has 3 strings , 5 floats. how convert list of lists numpy array? thanks!
you want structured array, 1 has compound dtype
:
a sample list of lists:
in [4]: ll = [['one','two',1,1.23],['four','five',4,34.3],['six','seven',4,34.3]]
trying make regular array, produces array of strings:
in [5]: np.array(ll) out[5]: array([['one', 'two', '1', '1.23'], ['four', 'five', '4', '34.3'], ['six', 'seven', '4', '34.3']], dtype='|s5')
but if specify dtype
contains 2 strings, , int , float, 1d structured array:
in [8]: np.array([tuple(x) x in ll],dtype='s5,s5,i,f') out[8]: array([('one', 'two', 1, 1.2300000190734863), ('four', 'five', 4, 34.29999923706055), ('six', 'seven', 4, 34.29999923706055)], dtype=[('f0', 's5'), ('f1', 's5'), ('f2', '<i4'), ('f3', '<f4')])
note had convert inner lists tuples. that's how structured array takes input, , how displays it. helps distinguish structured 'row' uniform 'row' of regular (2d) array.
this same sort of structured array genfromtxt
or loadtxt
produces when reading csv
file.
there other ways of specifying dtype
, , couple of other ways of loading data such array. start.
Comments
Post a Comment