使用python为数组中的所有n个唯一值创建n个被屏蔽的子数组 [英] Creating n number of masked subarrays for all the n unique values in an array using python
问题描述
我有一个从栅格创建的数组.该数组具有多个唯一值.我想为每个唯一值创建新的数组,以使具有该值的位置标记为"1",其余的标记为"0".我为此使用python.
I have an array created from a raster. This array has multiple unique values. I want to create new arrays for each unique value such that the places with that value are marked as '1' and the rest as '0'. I am using python for this.
A = [1, 1, 3, 2, 2, 1, 1, 3, 3] # Input array
b = numpy.unique(A) # gives unique values
a1 = [1, 1, 0, 0, 0, 1, 1, 0, 0] #new array for value 1
a2 = [0, 0, 0, 1, 1, 0, 0, 0, 0] #new array for value 2
a3 = [0, 0, 1, 0, 0, 0, 0, 1, 1] #new array for value 3
因此,基本上,代码将扫描唯一值,获取唯一值的数量,并为每个唯一值创建单独的数组.
So basically the code would scan through the unique values, get the number of unique values and create individual arrays for each unique value.
我已经使用numpy.unique()
和numpy.zeros()
来获取数组中的唯一值,并创建可以分别重写为所需数组的数组.但是我不怎么获取代码来获取唯一值的数量并创建那么多新数组.
I have used the numpy.unique()
and numpy.zeros()
to get the unique values in the array, and to create arrays that can be overwritten to the desired array, respectively. But I do not how to get the code to get the number of unique values and create that many new arrays.
我一直在尝试使用for loop
进行此操作,但是我没有成功.我开发这样的嵌套for loop
的概念还不是很清楚.
I have been trying to do this with the for loop
, but I haven't been successful. My concepts of developing such a nested for loop
are not very clear yet.
推荐答案
您可以执行以下操作:
>>> A = [1, 1, 3, 2, 2, 1, 1, 3, 3]
>>> result = [(A==unique_val).astype(int) for unique_val in np.unique(A)]
[array([1, 1, 0, 0, 0, 1, 1, 0, 0]), array([0, 0, 0, 1, 1, 0, 0, 0, 0]), array([0, 0, 1, 0, 0, 0, 0, 1, 1])]
该程序的核心部分是:
(A == unique_val).astype(int)
它只是将numpy数组中的元素与unique_val
进行比较,每个元素返回一个boolean
结果.通过使用astype(int)
,我们将布尔结果转换为整数数组.
It's simply comparing the elements in numpy array with unique_val
, each element return a boolean
result. By using astype(int)
we are converting the boolean result to an integer array.
这篇关于使用python为数组中的所有n个唯一值创建n个被屏蔽的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!