我有一个形状为x
的numpy ndarray (M,N)
,其中N
中的每个元素都是一个2元素元组,包含复数的实部和虚部。
我想将元组拆成另一个维度,以便我的x
现在将具有(M,N,2)
的形状
我的第一个想法是将实部和虚部分成两个(M,N)
形状的numpy数组,并在第二个轴上将它们连接起来,以便获得所需的输出。为此,我尝试仅按以下方式访问实部和虚部
x[:,:][0]
x[:,:][1]
但是,它将返回整个数组,而不是仅返回实部/虚部。关于如何进行的任何指示?
数组示例如下
array([[( 4.82641562, -1.84333128), (-1.29724314, 2.06545141),
( 0.02074953, -1.32518303)],
[(-0.81477981, -3.34148138), ( 0.231383 , 1.35495823),
( 1.66341462, -1.33603417)],
[( 2.2809137 , -1.17720382), (-1.05115026, -2.09556016),
( 1.57932884, -0.7438237 )],
[(-2.2170903 , 0.81147059), ( 0.17489367, 0.15123805),
(-1.95151614, -0.5669619 )],
[(-2.16413158, 0.44555251), ( 1.2545366 , -0.06933326),
( 1.08469658, 1.71108236)],
[(-0.99776606, -0.0607623 ), (-0.11785624, -1.90687216),
( 1.28964911, -1.03083365)],
[( 1.65550362, -1.26383881), ( 0.13404437, 1.4402823 ),
( 0.04223597, -1.00992713)],
[(-0.4696885 , 2.66014003), (-1.12157114, -1.03019938),
( 2.6312301 , 0.22770433)],
[( 1.74457246, -0.91478885), (-0.18861201, 0.75360561),
( 0.27141119, 0.71356903)],
[(-0.15940566, 1.26613812), ( 1.28238354, 1.31858431),
( 0.31217745, 0.13244299)]],
dtype=[('real', '<f8'), ('imag', '<f8')])
答案 0 :(得分:1)
您可以方便地将数组设置为structured array,这意味着您可以使用每个字段的字符串名称来访问实部和虚部:
arr['real']
arr['imag']
例如:
>>> arr['real']
array([[ 4.82641562, -1.29724314, 0.02074953],
[-0.81477981, 0.231383 , 1.66341462],
[ 2.2809137 , -1.05115026, 1.57932884],
[-2.2170903 , 0.17489367, -1.95151614],
[-2.16413158, 1.2545366 , 1.08469658],
[-0.99776606, -0.11785624, 1.28964911],
[ 1.65550362, 0.13404437, 0.04223597],
[-0.4696885 , -1.12157114, 2.6312301 ],
[ 1.74457246, -0.18861201, 0.27141119],
[-0.15940566, 1.28238354, 0.31217745]])
>>> arr['imag']
array([[-1.84333128, 2.06545141, -1.32518303],
[-3.34148138, 1.35495823, -1.33603417],
[-1.17720382, -2.09556016, -0.7438237 ],
[ 0.81147059, 0.15123805, -0.5669619 ],
[ 0.44555251, -0.06933326, 1.71108236],
[-0.0607623 , -1.90687216, -1.03083365],
[-1.26383881, 1.4402823 , -1.00992713],
[ 2.66014003, -1.03019938, 0.22770433],
[-0.91478885, 0.75360561, 0.71356903],
[ 1.26613812, 1.31858431, 0.13244299]])
答案 1 :(得分:0)
您可以尝试使用以下代码
[x[0] for x in arr]
实部和虚部
[x[1] for x in arr]