1

I have a tasty, empty array called fajita:

fajita = np.empty(2)
array([  2.00000000e+00,   1.72723382e-77])

When I use:

np.insert(fajita,0,[2,2])

I get:

array([  2.00000000e+00, 2.00000000e+00,   2.00000000e+00,   1.72723382e-77])

The problem here is that I only want the 2 values I inserted, I don't want to keep the previous values from the empty array. Expected output should be an array w/ only 2 values that were inserted. Something like:

array([  2.00000000e+00, 2.00000000e+00])
3
  • I think the empty is what I want, is there an alternative to insert? Commented Oct 28, 2017 at 7:17
  • I;ve tried that one Commented Oct 28, 2017 at 7:21
  • still doesn't work, I get the values I want but a bunch of 0's at the end Commented Oct 28, 2017 at 7:22

4 Answers 4

5

One way to do it with empty and slice setting :

import numpy as np
fajita = np.empty(2)
fajita[:] = [2, 2]

Yet another way to do it with fill :

fajita = np.empty(2)
fajita.fill(2)

Another solution would be to create the array directly with the values you want (I think this is what you should do, and that's one of the reasons why I didn't understand your question at first) :

fajita = np.array([2,2])
Sign up to request clarification or add additional context in comments.

Comments

1

Hope this helps

# When you want to replace your empty array/matrix
fajita = [2.00000000e+00, 2.00000000e+00]

Comments

1

You can do the following in my opinion:

  1. Create an empty array of the size you need (maybe a bit more in case you are not sure)

  2. Insert the data in the array where you want it to be The following example sequentially inserts the data (e.g. when reading multiple files and adding the data from the files into the array)

presized_array = np.empty(100) #presized empty arrray of size 100
data_chunk_one = np.arange(10) #dummy data that we want to insert
presized_array[0:9] = data_chunk_one #add the first data chunk

data_chunk_two = np.arange(10) #dummy data that we want to insert
presized_array[10:20] = data_chunk_two #add the second data chunk

... and so on for every additonal chunk

Comments

0

Or:

arr = np.empty(0)  # you want it to contain 0 elements
np.insert(arr, 0, [2,2])

6 Comments

i wanted to create a "pre-sized" array of the data I had
Then you should never use insert, which is for changing the size of arrays.
alright, so my question is what should I use instead?
Right, and that's answered above. The problem is you're misusing the word insert, which makes your question malformed. To python, that means "change the length of the list".
np.fill fills it all with the same value, is there a way to have it fill 10 different values at once?
|

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.