numpy read .csv with complex number

后端 未结 4 1098
-上瘾入骨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:15

    Import the csv file as an array of strings with genfromtxt(...) with dtype='str'. Then you can manipulate each entry with np.vectorize(...).

    import numpy as np
    from numpy import genfromtxt
    
    # import data as an array of strings using the dtype
    temp = genfromtxt('matlab_sim_Z.csv', delimiter=',',dtype='str')
    
    # perform elementwise conversion to complex numpers
    mapping = np.vectorize(lambda t:complex(t.replace('i','j')))
    data = mapping(temp)
    

    In a single line:

    data = np.vectorize(lambda t:complex(t.replace('i','j'))) (genfromtxt('matlab_sim_Z.csv', delimiter=',',dtype='str'))
    

提交回复
热议问题