-1

This is my current code:

#move data from vector, A, into 2D array, H
    for i in range(0,nlat):
        jmin = nheader+1+i*nlon
        jmax = nheader+(i+1)*nlon
        A = A[jmin:jmax+1]
        H[i] = A
        A = np.array(Alist)

I have a very long vector, and I am taking certain data from it and putting it into a 2D array of dimension nlat x nlon. This setup works but it is very time consuming. Any suggestion of how to speed it up or rewrite it so it doesn't take as long would be very helpful.

st123
  • 1
  • 2
  • 1
    `np.reshape(A, (nlat, nlon))` – Pranav Hosangadi Jun 04 '21 at 14:26
  • Does this answer your question? [Convert a 1D array to a 2D array in numpy](https://stackoverflow.com/questions/12575421/convert-a-1d-array-to-a-2d-array-in-numpy) – Pranav Hosangadi Jun 04 '21 at 14:27
  • Not really, because len(A) != nlat*nlon. It won't correctly translate that way. If you can tell by the code, I am taking, say, A[5:10] and putting that in H[0], then A[6:11] and putting that in H[1] and so on. This takes a while, but unfortunately reshaping doesn't do what I need it to. – st123 Jun 04 '21 at 14:35
  • What is `nlat` and `nlon` in your example? How about `nheader`? You can simply slice the vector and _then_ reshape if the purpose of this loop is to skip the header. `A[nheader+1:].reshape((nlat, nlon))`. Could you add an example input and output to your question to make it clearer? – Pranav Hosangadi Jun 04 '21 at 14:38
  • That might work. I'll give it a try and add an MRE if it doesn't work. Thanks – st123 Jun 04 '21 at 14:40
  • Your suggestion worked perfectly and so much faster. Thank you so much! – st123 Jun 04 '21 at 14:42

1 Answers1

0

You can use numpy.

import numpy as np

vector = np.array(A).reshape(nlat, nlon)
myz540
  • 537
  • 4
  • 7