There is a file containing complex numbers. I manage to unpack it in numpy.array, and I want to list, because the number of numbers is initially unknown, and the array, unlike the list, needs to be dimensioned immediately. Trying to use code

data[x,y]= complex(struct.unpack('f', f.read(4))[0], struct.unpack('f', f.read(4))[0]) 

The code works for np.array, if I try to use with a list, I get the error "list indices must be integers, not tuple"

    1 answer 1

    Why not use Numpy to write and read complex numbers?

    An example with a complex vector:

     In [75]: A1 = np.array([1+2j, 1-2j], dtype='complex128') In [76]: A1 Out[76]: array([1.+2.j, 1.-2.j]) In [77]: np.savetxt('d:/temp/A1.txt', A1.view('float')) In [78]: B1 = np.loadtxt('d:/temp/A1.txt').view('complex') In [79]: B1 Out[79]: array([1.+2.j, 1.-2.j]) In [80]: A1 == B1 Out[80]: array([ True, True]) 

    An example with a complex 2D matrix:

     In [81]: A2 = np.array( ...: [[1+2j, 1-2j], ...: [2+3j, 2-3j]], dtype='complex128') ...: ...: In [82]: np.savetxt('d:/temp/A2.txt', A2.view('float')) In [83]: B2 = np.loadtxt('d:/temp/A2.txt').view('complex') In [84]: B2 Out[84]: array([[1.+2.j, 1.-2.j], [2.+3.j, 2.-3.j]]) In [85]: A2 == B2 Out[85]: array([[ True, True], [ True, True]]) 
    • I have several files, I open one by one, I read sync words and caps in each one; if the header fits, I shift the complex numbers from under the caps to the array. the problem is that I don’t know in advance how many complex numbers there will be and I cannot create an array in advance. And saving to the text and then reading in my opinion is not particularly rational in my situation - lampochki
    • @lampochki, then try to read one by one "sync word" is still being read ... - MaxU