It would seem you're doing it the right way. One thing though: you might want to replace the following piece of code:
[[x[i]]*b[i] for i in range(len(x))]
A few points as to how you could improve this:
- I suggest you use
zip
to iterate over two arrays simultaneously. - Also, prefer using
()
over[]
, since it creates a generator expression, rather than a list. - A similar argument holds with the construct
join([ ... ])
. Simply usejoin( ... )
instead, which would avoid creating the list in memory. - Better variable names will also help with clarity.
([s] * count for s, count in zip(strings, counts))
Finally, formatting can make loads of difference:
import numpy as np
strings = ['yugoslavia', 'zealand', 'zimbabwe', 'zip', 'zone']
counts_array = np.array([[2,1,0,0,5], [0,0,1,3,0]])
result = np.apply_along_axis(
lambda counts: ' '.join(item for sublist in
([s] * count for s, count in zip(strings, counts))
for item in sublist),
1, y)
An equally ugly alternative might involve using two join statements:
result = np.apply_along_axis(
lambda counts: ' '.join(filter(None,
(' '.join([s] * count) for (s, count) in zip(strings, counts)))),
1, y)
Note how I've had to use filter
, as per this question, in order to remove the extra spaces emanating from the empty strings.