Basically, I have a bunch of data where the first column is a string (label) and the remaining columns are numeric values. I run the following:
data = numpy.genfromtxt('data.txt', delimiter = ',')
This reads most of the data well, but the label column just gets ‘nan’. How can I deal with this?
By default,
np.genfromtxtusesdtype=float: that’s why you string columns are converted to NaNs because, after all, they’re Not A Number…You can ask
np.genfromtxtto try to guess the actual type of your columns by usingdtype=None:You can access the columns by using their name, like
a['f0']…Using
dtype=Noneis a good trick if you don’t know what your columns should be. If you already know what type they should have, you can give an explicitdtype. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then useUsing an explicit
dtypeis much more efficient than usingdtype=Noneand is the recommended way.In both cases (
dtype=Noneor explicit, non-homogeneousdtype), you end up with a structured array.[Note: With
dtype=None, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]