Add single element to array in numpy
append()
creates a new array which can be the old array with the appended element.
I think it's more normal to use the proper method for adding an element:
a = numpy.append(a, a[0])
Insert element into numpy array
You can use numpy.insert
, though unlike list.insert
it returns a new array because arrays in NumPy have fixed size.
>>> import numpy as np
>>> a = np.asarray([1,2,3,4])
>>> np.insert(a, 2, 66)
array([ 1, 2, 66, 3, 4])
How to add items into a numpy array
Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list
will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.
That said, It's often unavoidable and the functions that do this are:
for 2-D arrays:
- np.hstack
- np.vstack
- np.column_stack
- np.row_stack
for 3-D arrays (the above plus):
- np.dstack
for N-D arrays:
- np.concatenate
Better way to insert elements into numpy array
Use range-offsetted indices with np.insert
-
np.insert(a, add_idx - np.arange(len(add_idx)), add_val)
Sample run -
In [20]: a
Out[20]: array([1, 3, 5])
In [21]: add_idx
Out[21]: [1, 3]
In [22]: add_val
Out[22]: [2, 4]
In [23]: np.insert(a, add_idx - np.arange(len(add_idx)), add_val)
Out[23]: array([1, 2, 3, 4, 5])
inserting values into numpy array
When you initialize a numpy array by np.empty()
, it allocates enough space for you, but the values inside these supposedly empty cells will be random rubbish. E.g.
>>> a = np.empty(5,dtype = int)
>>> a
array([-2305843009213693952, -2305843009213693952, 4336320554,
0, 0])
>>> k = np.empty(5,dtype = int)
>>> k
array([-2305843009213693952, -2305843009213693952, 4336320556,
4294967297, 140215654037360])
Hence, you have two choices: initilize an empty array with length 0 then append. NOTE: as @hpaulj pointed out, you need to set some array to be equal to the array returned by np.append()
i.e.
>>> a = np.array([],dtype = int)
>>> a = np.append(a,2)
>>> a = np.append(a,1)
>>> a = np.append(a,3)
>>> a = np.append(a,5)
>>> a
array([2, 1, 3, 5])
Or you can initialize by np.empty()
but then you have to use up all the cells that you initialized first before appending. i.e.
>>> a = np.empty(3,dtype = np.int)
>>> a[0] = 2
>>> a[1] = 1
>>> a[2] = 5
>>> a = np.append(a,3)
>>> a
array([2, 1, 5, 3])
Add element after each element in numpy array python
Use the numpy .zeros function !
import numpy as np
inputArray = [4,5,6]
newArray = np.zeros(5*len(inputArray),dtype=int)
newArray[::5] = inputArray
In fact, you 'force' all the values with indexes 0,5 and 10 to become 4,5 and 6.
so _____[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
becomes [4 0 0 0 0 5 0 0 0 0 6 0 0 0 0]
>>> newArray
array([4, 0, 0, 0, 0, 5, 0, 0, 0, 0, 6, 0, 0, 0 ,0])
Adding an array to a numpy array
Have a look at the docs for insert
and flatten
: They both return new arrays (copies). So you need to write
X = np.insert(a, [0, 0], toAppend)
in order for X
to contain the extended array. I also don't think you need the preceding X.flatten()
.
Instead of inserting into a numpy array (which is expensive), you should consider just building a nested list
and only convert it once at the end.
Prepend element to numpy array
numpy has an insert
function that's accesible via np.insert
with documentation.
You'll want to use it in this case like so:
X = np.insert(X, 0, 6., axis=0)
the first argument X
specifies the object to be inserted into.
The second argument 0
specifies where.
The third argument 6.
specifies what is to be inserted.
The fourth argument axis=0
specifies that the insertion should happen at position 0
for every column. We could've chosen rows but your X is a columns vector, so I figured we'd stay consistent.
Insert element at nth position in Array with numpy.insert
Inserting would take place altogether for both np.nan
. So, if you use [1,2]
then index 1 would be between 1
and 2
, and index 2 would be between 2
and 'test'
.
The position needs to be [1,1]
if you want to insert continuous values.
import numpy as np
position = [1,1]
array = np.array([1,2,'test', 3])
array = np.insert(array, position, np.nan)
print(array)
Output:
['1' 'nan' 'nan' '2' 'test' '3']
Related Topics
How to Do Assignments in a List Comprehension
Count Unique Values Using Pandas Groupby
Unnamed Python Objects Have the Same Id
How to Get Python Requests to Trust a Self Signed Ssl Certificate
How to Terminate a Thread When Main Program Ends
Attaching a Decorator to All Functions Within a Class
Python Pandas: How to Specify Data Types When Reading an Excel File
Retrieving a Foreign Key Value with Django-Rest-Framework Serializers
Find P-Value (Significance) in Scikit-Learn Linearregression
How to Get the Largest Integer One Can Use in Python
Compulsory Usage of If _Name_=="_Main_" in Windows While Using Multiprocessing
Comparing Python Dictionaries and Nested Dictionaries
Create a Day-Of-Week Column in a Pandas Dataframe Using Python
Explicitly Select Items from a List or Tuple
What Is the Time Complexity of Popping Elements from List in Python