如何将含两列纯双精度数的文件读取为NumPy复数数组?
How to read a two-column double-precision file into a NumPy complex array
No problem—since your input is just two space-separated columns (real part first, imaginary part second), we can skip the fancy string parsing used for formatted complex numbers and do this directly with NumPy's built-in tools.
Here's a straightforward solution:
import numpy as np # Load the text file into a 2D float array raw_data = np.loadtxt('example') # Combine the two columns into a complex array complex_array = raw_data[:, 0] + 1j * raw_data[:, 1]
How this works:
np.loadtxt('example')reads your file into an N×2 NumPy array, where each row corresponds to a line in the file, and the two columns are the real and imaginary values respectively.- We use array slicing (
raw_data[:, 0]) to grab all values from the first column (real parts) and multiply the second column (raw_data[:, 1]) by1j(NumPy's imaginary unit) to get the imaginary parts. Adding these together gives us a 1D complex array.
For your sample file:
0.8355544313622164 0
1.199174279986189 0
1.417275292218002 0
Running the code will produce this output:
print(complex_array) # Output: [0.83555443+0.j 1.19917428+0.j 1.41727529+0.j]
This method is efficient, works for any number of rows, and handles the double-precision values natively without extra parsing steps.
内容的提问来源于stack exchange,提问作者Herpes Free Engineer
相关产品推荐
相关产品推荐

