使用Numpy数组创建唯一数组
你能创建一个包含所有唯一值的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
只需要把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()
11
从一组数据中获取独特的随机样本,最方便的方法可能就是使用 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)