You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含两列纯双精度数的文件读取为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]) by 1j (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:56:19