1

My problem:

import numpy as np
import itertools

bla = list(itertools.product([0, 1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
np.random.choice(bla,size=3)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 1122, in mtrand.RandomState.choice
ValueError: a must be 1-dimensional

Now from what I understand numpy doesn't think of the tuples as objects inside my 1-dimensional array but as another array, turning the entire thin 2 dimensional. What is the best way to fix this?

WhySoSerious
  • 185
  • 1
  • 19
ZirconCode
  • 805
  • 2
  • 10
  • 24

2 Answers2

3

The problem you have is that numpy can accept only 1-D arrays, while you have a 2-D array (cause of tuple); to overcome this problem, if you need tuples, you can choice a random index in the interval and then get the element from that index.

idx = np.random.choice(len(bla))
elem = bla[idx]
crissal
  • 2,547
  • 7
  • 25
  • Thank you, this together with: test = np.random.choice(len(bla),size=4,replace=False); x = [bla[i] for i in test] solved my problem – ZirconCode Jun 29 '19 at 10:05
1

This Can help may be

Numpy: Get random set of rows from 2D array

bla = np.random.randint(2, size=(8,3))
bla[np.random.choice(bla.shape[0], 3, replace=False), :]
WhySoSerious
  • 185
  • 1
  • 19