[Python] Wrong column assignment with np.genfromtext if passed column order is not the same as...

Discussão em 'Python' iniciado por Stack, Maio 6, 2025.

  1. Stack

    Stack Membro Participativo

    This problem appeared in some larger code but I will give simple example:

    from io import StringIO
    import numpy as np

    example_data = "A B\na b\na b"

    data1 = np.genfromtxt(StringIO(example_data), usecols=["A", "B"], names=True, dtype=None)
    print(data1["A"], data1["B"]) # ['a' 'a'] ['b' 'b'] which is correct

    data2 = np.genfromtxt(StringIO(example_data), usecols=["B", "A"], names=True, dtype=None)
    print(data2["A"], data2["B"]) # ['b' 'b'] ['a' 'a'] which is not correct


    As you can see, if I change passed column order in regard of column order in file, I get wrong results. What's interesting is that dtypes are same:

    print(data1.dtype) # [('A', '<U1'), ('B', '<U1')]
    print(data2.dtype) # [('A', '<U1'), ('B', '<U1')]


    In this example it's not hard to sort column names before passing them, but in my case column names are gotten from some other part of system and it's not guaranteed that they will be in same order as those in file. I can probably circumvent that but I'm wondering if there is something wrong with my logic in this example or is there some kind of bug here.

    Any help is appreciated.

    Continue reading...

Compartilhe esta Página