0

I wonder if there is a trick to extending a numpy array with consecutive numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y

x=np.array([4,8,4,10])

y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])

Here the length between each element that I added was three. Speed is of the essence here. I need something like this for my column data to work in creating a sparse matrix.

Also, if I have an array such as

s=np.array([0,1])

is there a quick way to extend each element an arbitrary amount of times, lets say 4 for example:

s=np.array([0,0,0,0,1,1,1,1])
1
  • For the second half of your question, have a look at numpy.repeat or numpy.tile. Commented Oct 11, 2016 at 0:34

3 Answers 3

2

Broadcasted addition is probably the fastest

In [241]: (x[:,None]+np.arange(4)).ravel()
Out[241]: array([ 4,  5,  6,  7,  8,  9, 10, 11,  4,  5,  6,  7, 10, 11, 12, 13])

It gets trickier if adding different amounts for each sublist.

repeat is useful:

In [242]: np.repeat(np.array([0,1]),[3,4])
Out[242]: array([0, 0, 0, 1, 1, 1, 1])

tile is another good tool.

Sign up to request clarification or add additional context in comments.

1 Comment

All great methods guys, this one was fastest though. Mahalo!
0

I don't know a built-in function that does precisely that, but with some creativity you could do:

>>> x=np.array([4,8,4,10])
>>> np.array([x+i for i in range(4)]).T.ravel()
array([ 4,  5,  6,  7,  8,  9, 10, 11,  4,  5,  6,  7, 10, 11, 12, 13])

For the second half of your question, have a look at numpy.repeat and numpy.tile.

Comments

0

This works on lists:

def extend(myList, n):
    extensions = [range(x, x + n) for x in myList]
    return [item for sublist in extensions for item in sublist] # flatten

Use as follows:

extend([4, 8, 4, 10], 4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.