Is there a function in numpy that determines whether strings should be integers or floating point numbers and automatically converts them? For instance, I often have a colle
numpy.genfromtxt can guess dtypes if you set dtype=None
:
import numpy as np
import io
alist = [['1','a','.3'],
['2','b','-.5']]
f = io.BytesIO('\n'.join(' '.join(row) for row in alist))
arr = np.genfromtxt(f,dtype=None)
print(arr)
print(arr.dtype)
# [(1, 'a', 0.3) (2, 'b', -0.5)]
# [('f0', '<i4'), ('f1', '|S1'), ('f2', '<f8')]
Note that it would be better to apply np.genfromtxt
directly to your text file instead of creating the intermediate list List
(or what I called alist
). If you need to do some processing of the file before sending it to np.genfromtxt
, you could make a file-like object wrapper around the file which can do the processing and be passed to np.genfromtxt
.