Numpy.genfromtxt deleting square brackets in dtype.names

后端 未结 2 811
小蘑菇
小蘑菇 2020-12-20 00:40

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         


        
2条回答
  •  萌比男神i
    2020-12-20 00:55

    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', '

    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]', '

    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]', '

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

提交回复
热议问题