使用Numpy数组创建唯一数组

时间:2014-08-18 17:22:44

标签: python arrays numpy unique

你能创建一个包含所有唯一值的numpy数组吗?

myArray = numpy.random.random_integers(0,100,2500)
myArray.shape = (50,50)

所以这里我有一个给定的随机50x50 numpy数组,但我可以有非唯一值。有没有办法确保每个价值都是独一无二的?

谢谢

更新

我创建了一个基本函数来生成列表并填充一个唯一的整数。

        dist_x = math.sqrt(math.pow((extent.XMax - extent.XMin), 2))
        dist_y = math.sqrt(math.pow((extent.YMax - extent.YMin),2))
        col_x = int(dist_x / 100)
        col_y = int(dist_y / 100)
        if col_x % 100 > 0:
            col_x += 1
        if col_y % 100 > 0:
            col_y += 1
        print col_x, col_y, 249*169
        count = 1
        a = []

        for y in xrange(1, col_y + 1):
            row = []
            for x in xrange(1, col_x + 1):
                row.append(count)
                count += 1
            a.append(row)
            del row

        numpyArray = numpy.array(a)

有更好的方法吗?

由于

2 个答案:

答案 0 :(得分:6)

从集合中获取唯一随机样本的最便捷方式可能是np.random.choice replace=False

例如:

import numpy as np

# create a (5, 5) array containing unique integers drawn from [0, 100]
uarray = np.random.choice(np.arange(0, 101), replace=False, size=(5, 5))

# check that each item occurs only once
print((np.bincount(uarray.ravel()) == 1).all())
# True

如果replace=False您从中取样的设置必须至少与您尝试绘制的样本数量一样大:

np.random.choice(np.arange(0, 101), replace=False, size=(50, 50))
# ValueError: Cannot take a larger sample than population when 'replace=False'

如果您要查找的是1和数组中元素数之间的整数的随机排列,您还可以使用np.random.permutation,如下所示:

nrow, ncol = 5, 5
uarray = (np.random.permutation(nrow * ncol) + 1).reshape(nrow, ncol)

答案 1 :(得分:0)

只需使用replace = False。

import numpy as np


def generate():
    global x
    powerball = np.random.randint(1,27)
    numbers = np.random.choice(np.arange(1, 70), replace=False, size=(1, 5))
    x = numbers, powerball
    return x

generate()