• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Staging Ground badges

Earn badges by improving or asking questions in Staging Ground.

assigning values in a numpy array

I have a numpy array of zeros. For concreteness, suppose it's 2x3x4:

and suppose I have a 2x3 array of random integers from 0 to 3 (the index of the 3rd dimension of x).

How do I do the following assignments efficiently (edit: something that doesn't use for loops and works for x with any number of dimensions and any number of elements in each dimension)?

Thanks, James

  • variable-assignment

user1857751's user avatar

3 Answers 3

At the moment, I can only think of the “simple” version, which involves flattening along the first two dimensions. This code should work:

This yields (with my randomly-generated y ):

The key is, if you do an indexing using multiple numpy arrays ( advanced indexing ), numpy will use pairs of indices to index into the array.

Of course, make sure x and y are both either C-order or F-order — otherwise, the calls to reshape and flatten might give different orders.

illya's user avatar

  • This definitely works faster than the for loops I was using, and it seems to scale really well with the number of dimensions and number of elements in each dimension. Thanks. –  user1857751 Commented Nov 27, 2012 at 22:50

Use numpy.meshgrid () to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension.

I've renamed your array from x to a, and the array of indexes from y to z, for clarity.

EDIT: 4D example:

Alex I's user avatar

  • Thanks for the response. Do you know how to generalize this to a with any number of dimensions? –  user1857751 Commented Nov 27, 2012 at 23:09
  • @user1857751: yes, of course, it generalizes in a straightforward way. meshgrid to create vectors of indexes in all the dimensions that you do not want to lookup, and then use those to index the original array and the indexes you do want to look up. –  Alex I Commented Nov 28, 2012 at 0:21

will produce the desired result, IIRC. If the array dimensions never change, consider replacing the two for loops and their burden by

James Waldby - jwpat7's user avatar

  • 2 Thanks for the response, but the problem is that I need to do this efficiently for large arrays. In other words, I want to avoid for loops. –  user1857751 Commented Nov 27, 2012 at 22:03
  • I need code that will handle any dimensions for x, i.e. any number of dimensions or any number of elements in each dimension. –  user1857751 Commented Nov 27, 2012 at 22:13
  • I'm not highly familiar with numpy so I don't know if it has a relevant builtin function to do the job. Of course there are related routines argwhere, nonzero, where, and extract that can do the opposite eg can find the locations of non-zeros in an array –  James Waldby - jwpat7 Commented Nov 27, 2012 at 22:28

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged python arrays numpy variable-assignment or ask your own question .

  • The Overflow Blog
  • Rust is evolving from system-level language to UI and frontend development
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Feedback Requested: How do you use the tagged questions page?
  • Proposed designs to update the homepage for logged-in users

Hot Network Questions

  • How long would it take to get from the port of Riga to London by boat in the 1890s?
  • Are there any special actions that I should execute as a reviewer of a sloppy manuscript?
  • How long should a direct quote be in order to be put in quotation marks?
  • British Children's Educational Televison show from the 80's / 90's about an alien disguised as a chair
  • How does "attempting to influence a public servant by means of deceit" affect political activity?
  • A Simple, Theft-Proof Connecting Wall
  • Why is the foundation of a passive portfolio better than active?
  • Unable to bond two 2.5 Gbps Realtek RTL8156 Ethernet adapters via LACP on Linux
  • Does “redeeming quality” simply mean “positive quality” today?
  • How did “way to go” come to mean “well done”?
  • What does an ontic hidden variable quantum model achieve?
  • Why isn't Listable listed as an attribute of functions such as QuantityMagnitude and UnitConvert?
  • What does Kant mean by pure intuitions, and why are they not separate from the faculty of sensibility?
  • Can weapon special abilities be activated at the same time with a single command?
  • Limit file IO speed
  • How to remove the DUAL BIOS logo from the GA-G31M-ES2L boot screen?
  • A question on embedding of group and group isomorphism.
  • How to divide a rectangular box into smaller rectangular boxes?
  • Applying to two PhD positions under the same professor at the same time?
  • Help identifying a rare version of Fiend Folio
  • Is it possible to write every real function as the sum of an injection and a surjection?
  • Auxiliary gas heat for ductless HVAC
  • PostgreSQL unaccent and full text search for Arabic/Persian
  • Snap is throwing an authorization exception

numpy array assignment

IMAGES

  1. NumPy Arrays

    numpy array assignment

  2. Mathematical Operations in Python with Numpy

    numpy array assignment

  3. Python

    numpy array assignment

  4. Python Add 2 Numpy Arrays

    numpy array assignment

  5. Introduction to NumPy

    numpy array assignment

  6. Array : numpy 2D array assignment with 2D value and indices arrays

    numpy array assignment

VIDEO

  1. NUMPY ARRAY INDEXING

  2. COMP 3122 Python ASSIGNMENT_1

  3. Numpy Array Cncatenation

  4. NumPy Array Review

  5. Creating NumPy Array, part 1 #numpytutorial

  6. NxtWave Python Numpy Coding Assignment Problem-4

COMMENTS

  1. python

    Use numpy.meshgrid() to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension.