Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

NumPy Append Values to Array – Add Elements Easily in Python

NumPy Append Values to Array

In real-world programming, data is often dynamic.

You may need to add new values to an existing array while working with NumPy.

NumPy provides a simple function called:

np.append()

This function allows you to append values to arrays efficiently.


What is Array Appending?

Appending means:

Adding new elements to the end of an array

Example:

Before: [1, 2, 3]  
After: [1, 2, 3, 4]

Why Use np.append()?

  • Easy to add new data
  • Works with 1D and multi-dimensional arrays
  • Useful in data collection
  • Helps in dynamic datasets
  • Common in data preprocessing

1. Basic Array Append

import numpy as np

arr = np.array([1, 2, 3])

new_arr = np.append(arr, 4)

print(new_arr)

Output

[1 2 3 4]

2. Appending Multiple Values

arr = np.array([10, 20, 30])

new_arr = np.append(arr, [40, 50, 60])

print(new_arr)

Output

[10 20 30 40 50 60]

3. Appending to 2D Arrays

arr = np.array([[1, 2], [3, 4]])

new_arr = np.append(arr, [[5, 6]], axis=0)

print(new_arr)

Output

[[1 2]
[3 4]
[5 6]]

4. Appending Columns

arr = np.array([[1, 2], [3, 4]])

new_arr = np.append(arr, [[5], [6]], axis=1)

print(new_arr)

Output

[[1 2 5]
[3 4 6]]

5. Appending Without Axis

If axis is not defined, array is flattened.

arr = np.array([[1, 2], [3, 4]])

new_arr = np.append(arr, [5, 6])

print(new_arr)

Output

[1 2 3 4 5 6]

6. Appending Floating Values

arr = np.array([1.5, 2.5])

new_arr = np.append(arr, 3.5)

print(new_arr)

7. Appending String Values

arr = np.array(["A", "B"])

new_arr = np.append(arr, "C")

print(new_arr)

8. Real-World Example: Student Scores

scores = np.array([80, 85, 90])

scores = np.append(scores, 95)

print(scores)

9. Real-World Example: Sales Data

sales = np.array([100, 200, 300])

sales = np.append(sales, [400, 500])

print(sales)

10. Important Note

np.append() does NOT modify the original array.

It returns a new array.

arr = np.array([1, 2, 3])
arr = np.append(arr, 4)

Comparison Table

FunctionPurpose
np.append()          Add values
np.concatenate()          Merge arrays
np.insert()          Add at position

Advantages of np.append()

  • Simple syntax
  • Flexible usage
  • Works with different dimensions
  • Useful in data preprocessing
  • Beginner-friendly

Summary

NumPy append() allows you to add new values to arrays easily. It is widely used in data manipulation, preprocessing, and dynamic array building.

This functionality is part of NumPy and widely used in applications built with Python.


Conclusion

Appending values in NumPy is essential when working with dynamic datasets. With np.append(), you can easily extend arrays and manage data efficiently in Python.




Post a Comment

0 Comments