numpy loadtxt single line/row as list

前端 未结 3 1557

I have a data file with only one line like:

 1.2  2.1  3.2

I used numpy version 1.3.0 loadtxt to load it

 a,b,c = loadtxt(\         


        
3条回答
  •  情话喂你
    2021-01-12 13:21

    What is happening is that when you load the array you obtain a monodimensional one. When you unpack it, it obtain a set of numbers, i.e. array without dimension. This is because when you unpack an array, it decrease it's number of dimension by one. starting with a monodimensional array, it boil down to a simple number.

    If you test for the type of a, it is not a float, but a numpy.float, that has all the properties of an array but a void tuple as shape. So it is an array, just is not represented as one.

    If what you need is a monodimensional array with just one element, the simplest way is to reshape your array before unpacking it:

    #note the reshape function to transform the shape
    a,b,c = loadtxt("text.txt").reshape((-1,1))
    

    This gives you the expected result. What is happening is that whe reshaped it into a bidimensional array, so that when you unpack it, the number of dimensions go down to one.

    EDIT:

    If you need it to work normally for multidimensional array and to keep one-dimensional when you read onedimensional array, I thik that the best way is to read normally with loadtxt and reshape you arrays in a second phase, converting them to monodimensional if they are pure numbers

    a,b,c = loadtxt("text.txt",unpack=True)
    for e in [a,b,c]
        e.reshape(e.shape if e.shape else (-1,))
    

提交回复
热议问题