Reputation: 15466
I have a tuple
which contains a numpy.array
of arbitrary length along with scalars. Something like this:
(array([ 31.5, 31.6, 31.7, 31.8, 31.9, 32. , 32.1, 32.2, 32.3,
32.4, 32.5, 32.6, 32.7, 32.8, 32.9, 33. , 33.1, 33.2,
33.3, 33.4, 33.5, 33.6, 33.7, 33.8, 33.9, 34. , 34.1,
34.2, 34.3, 34.4, 34.5, 34.6, 34.7, 34.8, 34.9, 35. ,
35.1, 35.2]), 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0)
My result needs to pair each element of the numpy.array
with all the other elements in the tuple
. Challenge is that the numpy.array
appears in an arbitrary location within the tuple such that I cannot index with a guarantee.
The result needs to be an iterable (preferably a tuple
) of numpy.array
s, something like this:
(array([31.5, 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0]),
array([31.6, 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0]),
array([31.7, 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0]),
array([31.8, 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0]),
...
)
I have tried solutions presented here and here as well as itertools.product
. The SE solutions assume two independent arrays and itertools.product
is not the right solution either.
Upvotes: 1
Views: 163
Reputation: 1021
This is another way to do it if you are certain that your tuple contains only one np.Array
C = [z for z in A if type(z) is not np.ndarray]
B = np.array([np.append(y,C) for y in [np.nditer(x) for x in A if type(x) is np.ndarray][0]])
#B can be a tuple or a list
Upvotes: 1
Reputation: 9610
import numpy as np
x = (np.array([ 31.5, 31.6, 31.7, 31.8, 31.9, 32. , 32.1, 32.2, 32.3,
32.4, 32.5, 32.6, 32.7, 32.8, 32.9, 33. , 33.1, 33.2,
33.3, 33.4, 33.5, 33.6, 33.7, 33.8, 33.9, 34. , 34.1,
34.2, 34.3, 34.4, 34.5, 34.6, 34.7, 34.8, 34.9, 35. ,
35.1, 35.2]), 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0)
components = sorted(x, key=lambda xi: np.isscalar(xi))
prefixes = components[0]
suffix = components[1:]
result = tuple(np.array([xi]+suffix) for xi in x)
Upvotes: 1
Reputation:
If you don't know the position of the array
, you'll just have to find it. I would simply code it as follows:
from numpy import array, ndarray
a = (array([ 31.5, 31.6, 31.7, 31.8, 31.9, 32. , 32.1, 32.2, 32.3,
32.4, 32.5, 32.6, 32.7, 32.8, 32.9, 33. , 33.1, 33.2,
33.3, 33.4, 33.5, 33.6, 33.7, 33.8, 33.9, 34. , 34.1,
34.2, 34.3, 34.4, 34.5, 34.6, 34.7, 34.8, 34.9, 35. ,
35.1, 35.2]), 30.0, 0.0025, 0.0, 0.0027, 0.2791, 1.5, 1.0, 100.0)
for i, aa in enumerate(a):
if isinstance(aa, ndarray):
break
t = tuple(s for j, s in enumerate(a) if j != i)
newlist = []
for aa in a[i]:
newlist.append(array((aa,) + t)))
result = tuple(newlist)
Upvotes: 2