[Tutor] Python question
Peter Otten
__peter__ at web.de
Wed Apr 20 05:55:06 EDT 2022
On 18/04/2022 11:50, Eleonora Panini wrote:
> <https://stackoverflow.com/posts/71904558/timeline>
>
> I need help to do the following steps in Phyton:
>
> -my starting array is: array = np.random.rand(1024x11700)
>
> -I have to obtain an array 1024x23400 with the following characteristics:
> 25 columns(1024x25) of data and 25 columns (1024x25) of zeros
>
> So I thought to do a loop every 25 columns(1024x25), insert an array of
> zeros (1024x25) alternatevely every 25 columns, so I obtain an array
> 1024x23400..
>
> but I don't know how to do it in Phyton.. Can you help me? Thank you
Hello Eleonora,
in case you are still not working ;) on the problem here's some
spoon-feeding. My approach differs from what you sketched out above in
that I create a result matrix (i. e. your 1024x23400 beast) containing
only zeros and then copy parts of the original data (the 1024x25 chunks)
into that result matrix.
Notes:
- For aesthetic reasons I swapped rows and columns
- Numpy experts might do this differently
import numpy
def blowup(a, chunksize):
assert len(a.shape) == 2
if a.shape[0] % chunksize:
raise ValueError(
f"Number of matrix rows ({a.shape[0]}) "
f"must be a multiple of chunk size ({chunksize})."
)
# create a matrix of zeros with twice as many rows as 'a'
b = numpy.zeros((2 * a.shape[0], a.shape[1]))
# lazily split 'a' into sub-matrices with chunksize rows
chunks = (
a[start: start + chunksize]
for start in range(0, a.shape[0], chunksize)
)
# iterate over the sub-matrices and replace zeros in 'b' with those
# sub-matrices.
delta = 2 * chunksize
start = 0
for chunk in chunks:
b[start:start+chunksize] = chunk
start += delta
return b
# sample 6x3 matrix
a = numpy.arange(6 * 3, dtype=float).reshape((6, 3)) + 1
print(a)
# create 12x3 matrix with every two data rows followed by two rows of
# zeroes
b = blowup(a, 2)
print(b)
# 12x3 matrix with every three data rows followed by three rows of
# zeroes
print(blowup(a, 3))
# 3x3 matrix cannot be broken into chunks of two without rest
# --> ValueError
print(blowup(a[:3], 2))
More information about the Tutor
mailing list