First of all you need to import some functions of numpy:
from numpy.random import rand, randint
from numpy import array, argsort
Case 1:
a = rand(10,5)
b=[]
for i in range(len(a)):
n=3 #number of 1's
b.append((argsort(a[i])>=(len(a[i])-n))*1)
b=array(b)
Result:
print b
array([[ 1, 0, 0, 1, 1],
[ 1, 0, 0, 1, 1],
[ 0, 1, 0, 1, 1],
[ 1, 0, 1, 0, 1],
[ 1, 0, 0, 1, 1],
[ 1, 1, 0, 0, 1],
[ 0, 1, 1, 1, 0],
[ 0, 1, 1, 0, 1],
[ 1, 0, 1, 0, 1],
[ 0, 1, 1, 1, 0]])
Case 2:
a = rand(10,5)
b=[]
for i in range(len(a)):
n=3 #max number of 1's
n=randint(0,(n+1))
b.append((argsort(a[i])>=(len(a[i])-n))*1)
b=array(b)
Result:
print b
array([[ 0, 0, 1, 0, 0],
[ 0, 1, 0, 1, 0],
[ 1, 0, 1, 0, 1],
[ 0, 1, 1, 0, 0],
[ 1, 0, 1, 0, 0],
[ 1, 0, 0, 1, 1],
[ 0, 1, 1, 0, 1],
[ 1, 0, 1, 0, 0],
[ 1, 1, 0, 1, 0],
[ 1, 0, 1, 1, 0]])
I think that could work. To get the result i generate lists of random floats and with "argsort" see what of those are the n biggests of the list, then i filter them as ints (boolean*1-> int).