thomas.mac
thomas.mac

Reputation: 1256

Inserting values into a np.empty array , how to replace?

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])

Upvotes: 1

Views: 2598

Answers (4)

dajo
dajo

Reputation: 11

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

Upvotes: 1

Eric
Eric

Reputation: 97661

Or:

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

Upvotes: 0

Unatiel
Unatiel

Reputation: 1080

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])

Upvotes: 5

pissall
pissall

Reputation: 7419

Hope this helps

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

Upvotes: 1

Related Questions