简体   繁体   English

Numpy数组,花式索引,复数

[英]Numpy arrays, fancy indexing, complex numbers

The following code multiplies a part of the array by a number 以下代码将数组的一部分乘以数字

def mul_by_num(a,b):
    a[0:2] *= b


import numpy as np
a = np.ones(5,dtype=np.float64)
mul_by_num(a,1.0)
mul_by_num(a,1j) #Generates a warning (and casts to float!)

The second call generates a warning 第二个调用会生成警告

-c:2: ComplexWarning: Casting complex values to real discards the imaginary part

The question is, what is the most pythonic way to multiply parts of numpy arrays by complex/real numbers without messing with dtypes? 问题是,在没有混淆dtypes的情况下,通过复数/实数乘以numpy数组的部分的最pythonic方法是什么? I do not really want to convert an array to complex from the beginning, but the program in principle can get a complex input. 我真的不想从一开始就将数组转换为复数,但原则上该程序可以获得复杂的输入。

EDIT: 编辑:

I do not care about copying the full array, casting it to complex; 我不关心复制整个阵列,把它复制到复杂的阵列; But I want to avoid checking dtypes (ie, np.float32, np.float64, np.complex, np.int etc.) 但我想避免检查dtypes(即np.float32,np.float64,np.complex,np.int等)

You're going to need to convert the array to complex at some point, otherwise it won't be able to hold complex numbers. 你需要在某些时候将数组转换为复数,否则它将无法容纳复数。

The easiest way to convert an array to complex is to add 0j : 将数组转换为complex的最简单方法是添加0j

if (np.iscomplexobj(b)):
    a = a + 0j
a[0:2] *= b

note: not a += 0j as that will attempt to modify the array inplace, which won't work if it isn't complex already. 注意: 不是 a += 0j因为它会尝试修改数据,如果它已经很复杂,这将无法工作。

Since increasing the speed of calculating, numpy array makes sure that having same type. 由于增加了计算速度,numpy数组确保具有相同的类型。 May be you can try the python list or casting it. 也许你可以尝试python列表或者投射它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM