numpy loadtxt single line/row as list

前端 未结 3 1558

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:08

    Simply use the numpy's inbuit loadtxt parameter ndmin.

    a,b,c=np.loadtxt('data.dat',ndmin=2,unpack=True)
    

    output

    a=[1.2]
    
    0 讨论(0)
  • 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,))
    
    0 讨论(0)
  • 2021-01-12 13:25

    The simple way without using reshape is, to explicitly typecast the list

     a,b,c = loadtxt("data.dat", usecols(0,1,2), unpack=True)
     a,b,c = (a,b,c) if usi.shape else ([a], [b], [c])
    

    This works faster than the reshape!

    0 讨论(0)
提交回复
热议问题