Tutorial Numpy - NumPy Array Append
Numpy ha anche la funzione append per aggiungere dati all’array, proprio come l’operazione append alla list in Python. Ma in alcuni casi, append in NumPy è anche un po’ simile al metodo extend in Python list.
Array append
listeamo prima la sintassi di ndarray.append.
Parametri d’ingresso
| nome del parametro | tipo di dati | Descrizione |
|---|---|---|
arr |
array_like | Un array per aggiungere un elemento |
values |
array_like | Array aggiunto |
axis |
INT | L’asse lungo il quale sono annessi i values. |
Facciamo qualche esempio,
In[1]: import numpy as np
arrayA = np.arange(12).reshape(3, 4)
arrayB = np.ones((1, 4))
np.append(arrayA, arrayB)
Out[1]: array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 1.,
1., 1., 1.])
Quando non viene fornito axis, sia arr che values vengono appiattiti prima dell’operazione. Il risultato sarà un array 1-D. Nell’esempio precedente, non dobbiamo preoccuparci della forma di due array dati.
In[2]: np.append(arrayA, arrayB, axis=0)
Out[2]: array([[0., 1., 2., 3.],
[4., 5., 6., 7.],
[8., 9., 10., 11.],
[1., 1., 1., 1.]])
In[2]: np.append(arrayA, np.ones((1, 3)), axis=0)
---------------------------------------------------------------------------
ValueError Traceback(most recent call last)
<ipython-input-25-fe0fb14f5df8 > in < module > ()
--- -> 1 np.append(arrayA, np.ones((1, 3)), axis=0)
D: \ProgramData\Anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
5164 values = ravel(values)
5165 axis = arr.ndim-1
-> 5166 return concatenate((arr, values), axis=axis)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Quando axis è uguale a 0, i values dell’array saranno aggiunti a arr nella direzione della colonna. Alzerà il ValueError se due array dati non hanno la stessa lunghezza nella riga - ValueError: all the input array dimensions except for the concatenation axis must match exactly.
Si potrebbe provare da soli ad aggiungere i dati nella direzione della riga con il parametro axis=1.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook