0

I have a numpy array, a with shape (2501, 4). I want to reshape it into a 3 dimensional array, that is, the result shape should be: (x, y, 4).

How can I determine the integer values x and y in this case? I know if it was only one value that was unknown, I could use -1. For example:

b = a.reshape(-1, 41, 4)
b.shape  # (61, 41, 4)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Gathide
  • 899
  • 9
  • 19

2 Answers2

1

The problem is that there are possibly many solutions for this, with the most trivial ones being:

x = 1,    y = 2501
x = 2501, y = 1

Otherwise you can use all factors that evenly divide the number:

x = 41, y = 61
x = 61, y = 41

There are solutions for finding all factors of a number - it's called "prime factorization", for example this answer:

def primes(n):
    """Copied from https://stackoverflow.com/a/16996439/5393381 (author: Daniel Fischer)"""
    primfac = []
    d = 2
    while d*d <= n:
        while (n % d) == 0:
            primfac.append(d)
            n //= d
        d += 1
    if n > 1:
        primfac.append(n)
    return primfac

>>> primes(2501)
[41, 61]

Note that all combinations of the result are potential solutions. For example for 16 there are these solutions:

>>> primes(16)
[2, 2, 2, 2]

So any of the following possibilities would match your requirement:

 1 & 16
 2 &  8
 4 &  4
 8 &  2
16 &  1

So you can't automate this because someone "needs to decide" which one to pick.

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • "... you can't automate.." dampens my spirit. I hope someone proves it wrong, soon. – Gathide May 10 '17 at 17:49
  • @Gathide I already listed you the possible combinations, which one do you want? If you know in advance which combination you need (like "first found combination") it's definetly possible to automate. But your question doesn't mention any "conditions" so the correct answer is: you can't. – MSeifert May 10 '17 at 17:51
  • your answer is ok. I only hope that your suggestion on automation is proved wrong, even if it is in future. – Gathide May 10 '17 at 17:54
  • Well put. this is a remarkably patient attempt to answer a question based on a faulty premise. – user2699 Jul 06 '17 at 02:16
0

You can search for all factors of a number x in NumPy using

factors = numpy.where(x % numpy.arange(1, x // 2 + 1) == 0)  # array([1, 41, 61])
Nils Werner
  • 34,832
  • 7
  • 76
  • 98