假设我有一个二维复杂的 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
尝试:
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