屏蔽2D阵列并基于屏蔽索引在第二阵列上操作

时间:2018-05-25 12:28:01

标签: python arrays list numpy masked-array

我有一个读入并输出2D数组的函数。对于输入中等于0的每个索引,我希望输出是常量(在本例中为pi),否则我会对其执行一些数学运算。 E.g:

import numpy as np
import numpy.ma as ma

def my_func(x):

    mask = ma.where(x==0,x)

    # make an array of pi's the same size and shape as the input
    y = np.pi * np.ones(x)

    # psuedo-code bit I can't figure out
    y.not_masked = y**2

    return y 

my_array = [[0,1,2],[1,0,2],[1,2,0]]

result_array = my_func(my_array)

这应该给我以下内容:

result_array = [[3.14, 1, 4],[1, 3.14, 4], [1, 4, 3.14]]

即。它已将y**2应用于2D列表中不等于零的每个元素,并将所有零替换为pi。

我需要这个,因为我的功能将包括除法,我事先并不知道索引。我正在尝试将matlab教程从教科书转换为Python,这个功能让我感到难过!

由于

3 个答案:

答案 0 :(得分:4)

直接使用np.where()

<div class="container">
  <div class="background">B</div>
  <div class="foreground">F</div>
</div>

示例:

y = np.where(x, x**2, np.pi)

答案 1 :(得分:2)

试试这个:

my_array = np.array([[0,1,2],[1,0,2],[1,2,0]]).astype(float)

def my_func(x):

    mask = x == 0

    x[mask] = np.pi
    x[~mask] = x[~mask]**2  # or some other operation on x...

    return x

答案 2 :(得分:1)

我建议而不是使用蒙版,你可以使用布尔数组来实现你想要的。

def my_func(x):
    #create a boolean matrix, a, that has True where x==0 and
    #False where x!=0 

    a=x==0

    x[a]=np.pi

    #Use np.invert to flip where a is True and False so we can 
    #operate on the non-zero values of the array

    x[~a]=x[~a]**2

    return x #return the transformed array

my_array = np.array([[0.,1.,2.],[1.,0.,2.],[1.,2.,0.]])

result_array = my_func(my_array)

这给出了输出:

array([[ 3.14159265,  1.        ,  4.        ],
       [ 1.        ,  3.14159265,  4.        ],
       [ 1.        ,  4.        ,  3.14159265]])

请注意,我特意向函数传递了一个numpy数组,最初你传递了一个列表,当你尝试进行数学运算时会产生问题。还要注意我用1.而不是1来定义数组,以确保它是一个浮点数而不是整数数组,因为如果它是一个整数数组,当你设置等于pi的值时它将截断为3。

也许最好在函数中添加一个部分以检查输入参数的dtype,看看它是否是一个numpy数组而不是列表或其他对象,并且还要确保它包含浮点数,如果不是你可以相应调整。

编辑: 根据Scotty1的建议改为使用〜而不是反转(a)。

相关问题