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)!
1,2,3
4,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
1', '<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
1', '<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)!
1', '<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.