Gathide
Gathide

Reputation: 1157

How do you reshape numpy array when the resulting 2 dimensions are unknown?

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)

Upvotes: 0

Views: 897

Answers (2)

MSeifert
MSeifert

Reputation: 152715

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.

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36775

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])

Upvotes: 0

Related Questions