Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Create Array

NumPy offers various ways to create arrays with different shapes and content. Here are some common methods:



1. Creating Arrays from Python Lists or Tuples :

You can create NumPy arrays from Python lists or tuples using the np.array() function:

import numpy as np
# 1D array from a list
array_1d = np.array([1, 2, 3, 4, 5])
# 2D array from a nested list
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("1D Array:")
print(array_1d)
print("2D Array:")
print(array_2d)

2. Creating Arrays with Initial Values

You can create arrays filled with a specific value or a sequence of values using functions like np.zeros(), np.ones(), np.full(), np.arange(), and np.linspace():


import numpy as np
# 1D array filled with zeros
zeros_array = np.zeros(5)
# 2D array filled with ones
ones_array = np.ones((2, 3))
# 1D array filled with a specific value
full_array = np.full(4, 7)
# 1D array of evenly spaced values range_array = np.arange(1, 10, 2) # start, stop (exclusive), step
# 1D array of evenly spaced values with a specific number of elements
linspace_array = np.linspace(0, 1, 5) # start, stop, num
print("Zeros Array:")
print(zeros_array)
print("Ones Array:")
print(ones_array)
print("Full Array:")
print(full_array)
print("Range Array:")
print(range_array)
print("Linspace Array:")
print(linspace_array)


Creating Arrays with Random Values

NumPy provides functions to create arrays filled with random values using np.random.rand(), np.random.randn(), and np.random.randint():


import numpy as np
# 2D array of random values from a uniform distribution [0, 1 )
random_array_uniform = np.random.rand(3, 3)
# 2D array of random values from a standard normal distribution (mean=0, std=1)
random_array_normal = np.random.randn(2, 2)
# 2D array of random integer values within a specified range
random_array_int = np.random.randint(1, 10, (2, 3)) # low, high (exclusive), size
print("Random Array (Uniform Distribution):")
print(random_array_uniform)
print("Random Array (Normal Distribution):")
print(random_array_normal)
print("Random Integer Array:")
print(random_array_int)







Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java