numpy read .csv with complex number

后端 未结 4 1074
-上瘾入骨i
-上瘾入骨i 2021-01-07 03:43

stackoverflow,

I have a matrix containing complex numbers (ex. -2.2982235934153075E-11+2.1179547211742553E-9i) that I need to import to a numpy array. I\'ve been us

4条回答
  •  离开以前
    2021-01-07 04:07

    You can do:

    import numpy as np
    a = np.genfromtxt(filename, converters={0: lambda x: x.replace('i','j')},
                      dtype=str)
    a = np.complex_(a)
    

    Note that the converters parameter was required because your text file is using i to denote the imaginary part.

    It may be easier to convert your text file externally to replace all the i by j, avoiding a complicated converters argument in case you have many columns.

    If your textfile with imaginary numbers had the format:

     (-2.298223593415307508e-11+2.117954721174255306e-09j)
     (-2.298223593415307508e-11+2.117954721174255306e-09j)
     (-2.298223593415307508e-11+2.117954721174255306e-09j)
     (-2.298223593415307508e-11+2.117954721174255306e-09j)
     (-2.298223593415307508e-11+2.117954721174255306e-09j)
     (-2.298223593415307508e-11+2.117954721174255306e-09j)
     (-2.298223593415307508e-11+2.117954721174255306e-09j)
    

    Where you could read using only:

    a = np.loadtxt(filename).view(complex)
    

    for example...

提交回复
热议问题