2

I'm trying to read in data from files using numpy.genfromtxt. I set the names parameter to a comma-separated list of strings, such as

names = ['a', '[b]', 'c']

However, when the array is returned, the dtype.names value returns ('a', 'b', 'c')

The deletechars parameter is either not set or forced to be None. I've checked that creating a numpy.ndarray with a dtype that has a named column with square brackets preserves the square brackets, so it must be that genfromtxt is deleting the square brackets. Is there a way to turn off this unexpected feature?

Note, this behavior also occurs if the names parameter is set to True. I've tested this in numpy versions 1.6.1 and 1.9.9

krosbonz
  • 185
  • 2
  • 8

2 Answers2

2

I've complained about this field name mangling behavior before on the numpy issue tracker and mailing list. It has also cropped up in several previous questions on SO.

In fact, by default np.genfromtxt will mangle field names even if you specify them directly by passing a list of strings as the names= parameter:

import numpy as np
from io import BytesIO

s = '[5],name with spaces,(x-1)!\n1,2,3\n4,5,6'

x = np.genfromtxt(BytesIO(s), delimiter=',', names=True)
print(repr(x))
# array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], 
#       dtype=[('5', '<f4'), ('name_with_spaces', '<f4'), ('x1\n1', '<f4')])

names = s.split(',')[:3]
x = np.genfromtxt(BytesIO(s), delimiter=',', skip_header=1, names=names)
print(repr(x))
# array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], 
#       dtype=[('5', '<f4'), ('name_with_spaces', '<f4'), ('x1\n1', '<f4')])

This happens despite the fact that field names containing non-alphanumeric characters are perfectly legal:

x2 = np.empty(2, dtype=dtype)
x2[:] = [(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)]
print(repr(x2))
# array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], 
#       dtype=[('[5]', '<f4'), ('name with spaces', '<f4'), ('(x-1)!\n1', '<f4')])

The logic of this behavior escapes me.


As you've seen, passing None as the deletechars= argument is not enough to prevent this from happening, since this argument gets initialized internally to a set of default characters within numpy._iotools.NameValidator.

However, you can pass an empty sequence instead:

x = np.genfromtxt(BytesIO(s), delimiter=',', names=True, deletechars='')
print(repr(x))
# array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], 
#       dtype=[('[5]', '<f8'), ('name_with_spaces', '<f8'), ('(x-1)!', '<f8')])

This could be an empty string, list, tuple etc. It doesn't matter as long as its length is zero.

Community
  • 1
  • 1
ali_m
  • 71,714
  • 23
  • 223
  • 298
  • Thanks, ali_m. I saw this solution in a bug tracker [here](https://github.com/numpy/numpy/issues/2509). @unutbu, was considering correcting after the fact, but the empty parameter is much easier. Will test, then accept the answer. – krosbonz Feb 06 '16 at 01:20
  • Those characters may ok in a structured array dtype, but not as attribute names for a recarray. I see that same sort of tension in `argparse` - do you give the user enough rope to hang themself? – hpaulj Feb 06 '16 at 03:18
  • @hpaulj Nope - they are also legal for recarrays (although of course you can't use the `.attribute`-style syntax to access them). Whether or not they *should* be legal is another question, but my point is that `np.genfromtxt` should not arbitrarily mess with legal field names. – ali_m Feb 06 '16 at 03:28
  • `loadtxt` uses `dtype=np.dtype([('a','i'),('[b]','f'),('c','f')])` without change. – hpaulj Feb 06 '16 at 03:39
  • I just noticed that as well - that may have changed in the most recent release. My other objections still stand, though :-) – ali_m Feb 06 '16 at 03:42
2

In String formatting issue (parantheses vs underline) I found that dtype=None is required in addition to the deletechars parameter:

https://stackoverflow.com/a/32540939/901925

In [168]: np.genfromtxt([b'1,2,3'],names=['a','[b]','xcx'],delimiter=',',deletechars='',dtype=None)
Out[168]: 
array((1, 2, 3), 
      dtype=[('a', '<i4'), ('[b]', '<i4'), ('xcx', '<i4')])

With the default dtype (float), deletechars is used, but the names pass through a second validator, easy_dtype which does not get this parameter.

In [170]: np.genfromtxt([b'1,2,3'],names=['a','[b]','xcx'],delimiter=',',deletechars='x')
Out[170]: 
array((1.0, 2.0, 3.0), 
      dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])

https://github.com/numpy/numpy/pull/4649


Field names can be changed after loading:

In [205]: data=np.genfromtxt([b'1 2 3 txt'],names=['a','b','c','d'],dtype=[int,float,int,'S4'])

In [206]: data.dtype.names
Out[206]: ('a', 'b', 'c', 'd')

In [207]: data.dtype.names=['a','[b]','*c*','d']

In [208]: data
Out[208]: 
array((1, 2.0, 3, 'txt'), 
      dtype=[('a', '<i4'), ('[b]', '<f8'), ('*c*', '<i4'), ('d', 'S4')])

This works for names taken from the file itself:

In [212]: data=np.genfromtxt([b'a [b] *c* d','1 2 3 txt'],dtype=[int,float,int,'S4'],names=True)
Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • indeed, without `dtype=None`, the answer given by @ali_m doesn't work. unfortunately, i can't specify `dtype=None` because i don't want all of the data to be read in as strings and not automatically cast to something else by genfromtxt. i'm instead left to write my own file reading routine. – krosbonz Feb 09 '16 at 00:53
  • 1
    Why not use simple field names during loading, and change them to something with funny characters afterwards? See my edit. – hpaulj Feb 09 '16 at 01:11
  • While it is possible to modify the array's `dtype.names` after the fact, doing so still requires code modification, as I don't know _a priori_ which line in the input files contain the header information. There are several different input file formats, and, in some cases, I use `genfromtxt` built-in features to determine which line contains the column names. Since I now have to write code that reads in the files to determine the `names` parameter, I might as well just write the code to read in the data themselves, as well. – krosbonz Feb 09 '16 at 20:13