Creating NumPy Arrays (arange, linspace, zeros, ones)

πŸ“Œ Introduction

Creating arrays is the first practical step when working with NumPy.

NumPy provides multiple powerful functions to generate arrays quickly and efficiently.


πŸ”’ Why Use NumPy Array Creation Functions?

Instead of manually writing data, NumPy allows you to:

  • Generate large datasets instantly
  • Create structured arrays
  • Save time in data processing

πŸ§ͺ 1. Creating Array using array()

This is the most basic method.

import numpy as nparr = np.array([1, 2, 3, 4])
print(arr)

πŸ” 2. Using arange()

Works like Python’s range() but returns a NumPy array.

import numpy as nparr = np.arange(0, 10, 2)
print(arr)

πŸ‘‰ Output:

[0 2 4 6 8]

βœ” Syntax:

np.arange(start, stop, step)

πŸ“ 3. Using linspace()

Generates evenly spaced numbers between a range.

import numpy as nparr = np.linspace(0, 1, 5)
print(arr)

πŸ‘‰ Output:

[0.   0.25 0.5  0.75 1.  ]

βœ” Syntax:

np.linspace(start, stop, number_of_values)

βšͺ 4. Using zeros()

Creates an array filled with zeros.

import numpy as nparr = np.zeros((2, 3))
print(arr)

πŸ‘‰ Output:

[[0. 0. 0.]
[0. 0. 0.]]

⚫ 5. Using ones()

Creates an array filled with ones.

import numpy as nparr = np.ones((2, 3))
print(arr)

πŸ‘‰ Output:

[[1. 1. 1.]
[1. 1. 1.]]

πŸ”’ Bonus: eye() (Identity Matrix)

import numpy as nparr = np.eye(3)
print(arr)

πŸ‘‰ Output:

[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

πŸ“Š Comparison Table

FunctionPurpose
array()Create from list
arange()Range with step
linspace()Equal spacing
zeros()Fill with 0
ones()Fill with 1
eye()Identity matrix

🧠 Pro Tips

  • Use arange() for step-based sequences
  • Use linspace() for precise spacing
  • Use zeros() & ones() for initialization

πŸ”— Works with Other Libraries

These arrays are used directly in:

  • Pandas
  • Matplotlib
  • TensorFlow

πŸ”š Conclusion

Mastering array creation in NumPy will make your data handling faster and more efficient.


Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *