In [228]: txt="""m/z, Lipid ID
...: 885.5, PI 18:0_20:4
...: 857.5, PI 16:0_20:4
...: 834.5, PS 18:0_22:6
...: 810.5, PS 18:0_20:4
...: 790.5, PE 18:0_22:6
...: """
genfromtxt has a lot of possible parameters. It's not as fast as the pandas equivalent, but still quite flixible.
In [229]: data = np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None, encoding=None,
names=True, autostrip=True)
In [230]: data
Out[230]:
array([(885.5, 'PI 18:0_20:4'), (857.5, 'PI 16:0_20:4'),
(834.5, 'PS 18:0_22:6'), (810.5, 'PS 18:0_20:4'),
(790.5, 'PE 18:0_22:6')],
dtype=[('mz', '<f8'), ('Lipid_ID', '<U12')])
This is a structured array, with 2 fields. Because of the names parameter, field names are taken from the file header line. With dtype=None, it deduces a dtype for each column, in this case float and string. Fields are accessed by name:
In [231]: data['Lipid_ID']
Out[231]:
array(['PI 18:0_20:4', 'PI 16:0_20:4', 'PS 18:0_22:6', 'PS 18:0_20:4',
'PE 18:0_22:6'], dtype='<U12')
In [232]: data['mz']
Out[232]: array([885.5, 857.5, 834.5, 810.5, 790.5])
To make a 2d array we have to cast it to object dtype, allowing a mix of numbers and strings.
In [233]: np.array(data.tolist(), object)
Out[233]:
array([[885.5, 'PI 18:0_20:4'],
[857.5, 'PI 16:0_20:4'],
[834.5, 'PS 18:0_22:6'],
[810.5, 'PS 18:0_20:4'],
[790.5, 'PE 18:0_22:6']], dtype=object)
The structured arrays can be loaded into a dataframe, with a result similar to what a pandas read would produce:
In [235]: pd.DataFrame(data)
Out[235]:
mz Lipid_ID
0 885.5 PI 18:0_20:4
1 857.5 PI 16:0_20:4
2 834.5 PS 18:0_22:6
3 810.5 PS 18:0_20:4
4 790.5 PE 18:0_22:6
Dataframe to_records produces a structured array, much like what we started with.
In [238]: _235.to_records(index=False)
Out[238]:
rec.array([(885.5, 'PI 18:0_20:4'), (857.5, 'PI 16:0_20:4'),
(834.5, 'PS 18:0_22:6'), (810.5, 'PS 18:0_20:4'),
(790.5, 'PE 18:0_22:6')],
dtype=[('mz', '<f8'), ('Lipid_ID', 'O')])
) characters in a row or tabs (\t`)?,?