Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

python - Resizing and stretching a NumPy array

I am working in Python and I have a NumPy array like this:

[1,5,9]
[2,7,3]
[8,4,6]

How do I stretch it to something like the following?

[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]

These are just some example arrays, I will actually be resizing several sizes of arrays, not just these.

I'm new at this, and I just can't seem to wrap my head around what I need to do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@KennyTM's answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try np.repeat:

>>> a = np.array([[1, 5, 9],
              [2, 7, 3],
              [8, 4, 6]])

>>> np.repeat(a,2, axis=1)
array([[1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6]])

So, this accomplishes repeating along one axis, to get it along multiple axes (as you might want), simply nest the np.repeat calls:

>>> np.repeat(np.repeat(a,2, axis=0), 2, axis=1)
array([[1, 1, 5, 5, 9, 9],
       [1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6],
       [8, 8, 4, 4, 6, 6]])

You can also vary the number of repeats for any initial row or column. For example, if you wanted two repeats of each row aside from the last row:

>>> np.repeat(a, [2,2,1], axis=0)
array([[1, 5, 9],
       [1, 5, 9],
       [2, 7, 3],
       [2, 7, 3],
       [8, 4, 6]])

Here when the second argument is a list it specifies a row-wise (rows in this case because axis=0) repeats for each row.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...