从 2D 复杂 numpy 数组写一个 dat 文件

问题描述 投票:0回答:1

假设我有一个二维复杂的 numpy 数组,如下所示:

import numpy as np
xl=np.linspace(0,2,num=3)
yl=np.linspace(0,1,num=2)
xm,ym=np.meshgrid( xl, yl, sparse=True, indexing='ij' )
z=xm**2+1j*ym
print(z)

如何将二维数组导出为以下形式的dat文件?

  x    y    Re(z)   Im(z)
  0    0     0       0
  0    1     0       1
  1    0     1       0
  1    1     1       1
  2    0     4       0
  2    1     4       1
python pandas numpy multidimensional-array
1个回答
0
投票

尝试:

import pandas as pd

x, y = np.indices(z.shape, sparse=True)
x, y = x.ravel(), y.ravel()

data = []
for i in x:
    for j in y:
        n = z[i][j]
        data.append((i, j, n.real, n.imag))

df = pd.DataFrame(data, columns='x y Re(z) Im(z)'.split())
df = df.astype(int)
print(df.to_csv(index=False, sep='\t'))

印花:

x       y       Re(z)   Im(z)
0       0       0       0
0       1       0       1
1       0       1       0
1       1       1       1
2       0       4       0
2       1       4       1
© www.soinside.com 2019 - 2024. All rights reserved.