append()
The append()
function in NumPy is used to append values to the end of an array. It adds new elements to the end of the original array and returns the new array with the appended values. The original array remains unchanged.
Syntax
The basic syntax for using the append()
function in NumPy is as follows:
np.append(arr, values, axis=None)
Here, arr
is the input array, values
are the values to be appended, and axis
is the axis along which the values are appended. If axis
is not specified, the values are appended to a flattened array.
Example
Consider the following example where we append values to a NumPy array:
import numpy as np
x = np.array([1, 2, 3])
y = np.append(x, [4, 5, 6])
print(y)
Here, we first create a NumPy array x
with the values [1, 2, 3]
. We then use the append()
function to append the values [4, 5, 6]
to the end of the array. The output of the code is: [1 2 3 4 5 6]
.
Output
The output of the append()
function is a new array with the appended values. The original array remains unchanged.
Explanation
The append()
function in NumPy is used to add new elements to the end of an array. It takes the original array and the values to be appended as input, and returns a new array with the added values. The axis
parameter specifies the axis along which the values are appended. If it is not specified, the values are appended to a flattened array.
Use
The append()
function is useful when you need to add new elements to an existing NumPy array. It can also be used to combine multiple arrays into a larger array. The function is commonly used in data analysis and scientific computing applications.
Important Points
- The
append()
function does not modify the original array. Instead, it returns a new array with the appended values. - You can use the
axis
parameter to control where the values are appended. - The
values
parameter can be a single value or a sequence of values to be appended to the array.
Summary
The append()
function in NumPy is used to add new elements to the end of an array. It takes the original array and the values to be appended as input, and returns a new array with the added values. The function is useful when you need to add new elements to an existing array or combine multiple arrays into a larger array. The axis
parameter can be used to control where the values are appended.