Numpy:从 2 个真实数组创建一个复杂数组? [英] Numpy: Creating a complex array from 2 real ones?

查看:24
本文介绍了Numpy:从 2 个真实数组创建一个复杂数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将同一个数组的 2 个部分组合成一个复杂的数组:

I want to combine 2 parts of the same array to make a complex array:

Data[:,:,:,0] , Data[:,:,:,1]

这些不起作用:

x = np.complex(Data[:,:,:,0], Data[:,:,:,1])
x = complex(Data[:,:,:,0], Data[:,:,:,1])

我错过了什么吗?numpy 不喜欢对复数执行数组函数吗?这是错误:

Am I missing something? Does numpy not like performing array functions on complex numbers? Here's the error:

TypeError: only length-1 arrays can be converted to Python scalars

推荐答案

这似乎符合您的要求:

numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)

这是另一种解决方案:

# The ellipsis is equivalent here to ":,:,:"...
numpy.vectorize(complex)(Data[...,0], Data[...,1])

还有一个更简单的解决方案:

And yet another simpler solution:

Data[...,0] + 1j * Data[...,1]

PS:如果要节省内存(无中间数组):

PS: If you want to save memory (no intermediate array):

result = 1j*Data[...,1]; result += Data[...,0]

下面的 devS 解决方案也很快.

devS' solution below is also fast.

这篇关于Numpy:从 2 个真实数组创建一个复杂数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆