In this Numpy tutorial, we will learn how to use a 2-dimensional NumPy array in Python. Also, we will cover these topics.
- Python NumPy 2d array slicing
- Python NumPy 2d array initialize
- Python NumPy 2d array indexing
- Python NumPy 2d array of zeros
- Python NumPy 2d array to 1d
- Python NumPy 2d array append
- Python NumPy 2d array declaration
- Python NumPy 2d array size
- Python NumPy 2d array to 3d
- Python 2d array without numpy
- Python numpy where 2d array
- Python numpy empty 2d array
- Python sort 2d numpy array by column
- Python numpy concatenate 2d array
- Python numpy 2d array to CSV
- Python numpy 2d array reshape
- Python numpy rotate 2d array
- Python numpy random 2d array
- Python numpy 2d array to string
- Python numpy transpose 2d array
- Python NumPy unique 2d array
- Python iterate numpy 2d array
- Python numpy 2d array of zeros
- Python find index of value in Numpy 2d array
- Python plot numpy 2d array
- Python numpy argmax 2d array
- Python numpy average 2d array
- Python numpy stack 2d array
- Python numpy shuffle 2d array
- Python numpy filter two dimensional array by condition
Python NumPy 2d array
- In this section, we will discuss how to create a 2-dimensional array in Python.
- In Python to create a 2-dimensional array, we can easily apply the np.array function. This function basically consumes less memory and stores data systematically.
Syntax:
Here is the Syntax of numpy.array() function
numpy.array
(
object,
dtype=None,
copy=True,
order='K',
subok=False,
ndim=0,
like=None
)
Example:
import numpy as np
arr1 = np.array([[23,67],[78,92]])
print(arr1)
In the above code first, we have imported a numpy library and then create a variable ‘arr1’ and assign a numpy array function for creating a 2-dimensional array.
Here is the Screenshot of the following given code
Another example to create a 2-dimension array in Python
By using the np.arange() and reshape() method, we can perform this particular task. In Python the numpy.arange() function is based on numerical range and it is an inbuilt numpy function that always returns a ndarray object. While np.reshape() method is used to shape a numpy array without updating its data.
Source Code:
import numpy as np
new_arr = np.arange(12).reshape(3,4)
print(new_arr)
In the above example, we have applied the np.arange() and reshape() method for creating a two-dimensional array. Once you will print the ‘new_arr’ then the output will display the 0-12 integer numbers.
Here is the Output of the following given code
Read: Python NumPy Array
Python NumPy 2d array slicing
- Let us see how to create a 2-dimensional array by using the slicing method in Python.
- In this example, we have to extract the first and last item of the numpy array. To do this task we are going to apply the [:2] slicing method that contains the first and last two elements.
Example:
import numpy as np
arr1 = np.array([[[67, 23, 89], [21, 31, 89], [64, 89, 91]],
[[78, 993, 56], [31, 22, 88], [120, 805, 190]],
])
result= arr1[:2, 1:, :2]
print("slicing array:",result)
You can refer to the below Screenshot
Another method for creating a 2-dimensional array by using the slicing method
In this example, we are going to use numpy.ix_() function.In Python, this method takes n number of one or two-dimensional sequences and this function will help the user for slicing arrays.
Syntax:
Here is the Syntax of numpy.ix() function
numpy.ix(*args)
Example:
import numpy as np
new_arr = np.arange(12).reshape(3,4)
print(new_arr)
result = new_arr[np.ix_([2,1],[0,2])]
print(result)
Here is the execution of the following given code
Read: Python NumPy zeros + Examples
Python NumPy 2d array initialize
- Here we can see how to initialize a numpy 2-dimensional array by using Python.
- By using the np.empty() method we can easily create a numpy array without declaring the entries of a given shape and datatype. In Python, this method doesn’t set the numpy array values to zeros.
- In this program, we will also use the append() function for merging two arrays and storing them into a given empty array and this function always returns a new array.
Syntax:
Here is the Syntax of numpy.empty() function
numpy.empty
(
shape,
dtype=float,
order='c',
like=None
)
Source Code:
import numpy as np
out1 = np.empty((0, 3), int)
out1 = np.append(out1, np.array([[78, 68, 92, 56]]), axis=0)
out1 = np.append(out1, np.array([[98, 11, 34, 89]]), axis=0)
print(out1)
In the above program, we have initialized an empty array and then use the numpy append() function for adding items in it. Once you will print the ‘out1’ then the output will display the new 2-dimensional array.
Here is the Screenshot of the following given code
Read: Python NumPy arange + Examples
Python NumPy 2d array indexing
- In this section, we will discuss how to get the index number of the numpy array by using Python.
- To perform this particular task first we will create an array by using the np.array() function and then declare a variable ‘b’ in which we are going to select the index number which we want to display in the output.
Example:
import numpy as np
arr1 = np.array([[67, 23], [21, 31]])
b= arr1[1]
print(b)
Here is the implementation of the following given code
As you can see in the Screenshot the output has displayed the second numpy array.
Read: Python NumPy Sum + Examples
Python NumPy 2d array of zeros
- In this program, we will discuss how to create a two-dimensional array with zeros values in Python.
- In this example, we are going to use the numpy zeros function for creating a new array that is filled with zeros and this method indicates to specify the exact dimension of the numpy array.
Syntax:
Here is the Syntax of numpy.zeros() function
numpy.zeros
(
shape,
dtype=float,
order='C',
like=None
)
Source Code:
import numpy as np
arr1 = np.zeros((3, 3))
print(arr1)
In the above program, we have used the np.zeros() function in which assigned the shape of the array elements. Now once you will print the ‘arr1’ then it will display a 2d array of 3 rows and 3 columns filled with zeros.
Read: Python NumPy matrix + Examples
Python NumPy 2d array to 1d
- In this section, we will discuss how to convert a 2-dimensional array into a 1-dimensional array.
- By using the flatten method we can solve this problem and this function returns a copy of the array in a one-dimensional array.
- In Python, the flatten() method changes the shape of an array and it will help the user to convert the 2-dimensional array into a one-dimensional array.
Syntax:
Here is the Syntax of numpy.flatten() method
ndarray.flatten
(
order='C'
)
Source Code:
import numpy as np
arr1 = np.array([[67, 23, 89], [21, 31, 89], [64, 89, 91]])
result=arr1.flatten()
print(result)
In the above code, we have imported the numpy library with alias ‘np’ and we will use the np.array() function to create an array of integers. Now in this example, we are going to flatten our 2-dimensional array by using ndarray.flatten().
You can refer to the below Screenshot
Another example to convert 2-d array to 1-d array by using ravel() method
By using numpy.ravel() method we can get the output in 1-dimension array form. In Python, this method will always be returned a numpy array that has the same datatype and if the array is a masked array then it will return a masked numpy array.
Syntax:
Here is the Syntax of numpy.ravel() method
numpy.ravel(
a,
order='C'
)
Example:
Let’s take an example and check how to convert 2-d array to 1-d array
import numpy as np
new_val = np.array([[45, 34, 56],
[118, 192, 765],
[356, 563, 932]])
new_result = np.ravel(new_val)
print("Convert 2d to 1-d:",new_result)
Here is the Screenshot of the following given code
Read: Python NumPy append + 9 Examples
Python NumPy 2d array append
- In this Program we will discuss how to append 2-dimensional array in Python.
- In Python the numpy.append() function is available in the Numpy module and this function will help the user to add new items to a given array or in simple words we can say merge two different arrays by using the np.append() function and it will return a new array with same shape and dimension
Syntax:
Here is the Syntax of numpy.append() function
numpy.append
(
arr,
values,
axis=None
)
Example:
import numpy as np
arr1 = np.array([[178, 667], [190, 567]])
arr2 = np.array([[888, 128], [24, 76]])
new_res = np.append(arr1, arr2,axis=1)
print(new_res)
In the above program, we have imported a numpy library and then create two different arrays by using np.array. Now we want to append these arrays and store them into ‘new_res’ variable. Once you will print ‘new_res’ then the output will display a new numpy array.
Here is the Screenshot of the following given code
Read: Python sort NumPy array + Examples
Python NumPy 2d array declaration
- Here we can see how to declare a numpy 2-dimensional array in Python.
- In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.
Source Code:
import numpy as np
new_arr=np.arange(8)
new_result=new_arr.reshape(2,4)
print(new_result)
Here is the output of the following given code
Read: Python NumPy concatenate
Python NumPy 2d array size
- Let us see how to get the size of a numpy 2-dimensional array in Python.
- In Python the size() attribute always return the size of a numpy array that means it counts the number of items of the numpy array and then display it.
Syntax:
Here is the Syntax of ndarray size()
numpy.ndarray.size()
Example:
import numpy as np
new_array = np.array([[34, 15], [78, 98], [23, 78]])
print("size of 2-dimension aray is: ", new_array.size)
You can refer to the below Screenshot
As you can see in the Screenshot the output is 6.
Read: Python NumPy linspace + Examples
Python NumPy 2d array to 3d
- In this section, we will discuss how to convert 2-dimensional array into 3-dimensional array.
- In Python to convert a 2-dimension array to a 3-dimensional array, we can easily use the numpy.reshape() method. This function will shape the array without updating its element.
Syntax:
Here is the Syntax of numpy.reshape() method
numpy.reshape
(
a,
newshape,
order='C'
)
Example:
import numpy as np
new_val = np.array([[78,98,345,667,765,982],
[16,78,228,934,578,309]])
new_result = np.reshape(new_val, (4, 3))
print(new_result)
In the above code we have used the np.reshape() method for converting a two-dimensional array to a 3-dimensional array. In this method, we have assigned the shape and the dimension size of the new array.
Here is the implementation of the following given code
Read: Python NumPy where with examples
Python 2d array without numpy
- In this section, we will discuss how to create a 2-dimensional array in Python without using a numpy package.
- In this example first, we have selected the no of arrays and then create a variable ‘new_val’ in which we have to assign a list comprehension method with range attribute.
Source Code:
Z = 4
new_val = [[1] * Z for i in range(Z)]
print(new_val)
Here is the implementation of the following given code
As you can see in the Screenshot the output is displaying 2-d array filled with 1’s value.
Read: Python NumPy read CSV
Python numpy where 2d array
- Here we can use the concept of where() function for getting the index number of particular element.
- In Python the numpy.where() function is used to choose items from a numpy array based on a given condition. It will check the condition if the given value is not matched with array and y argument is not passed then it will return an empty array along with datatype.
Syntax:
Here is the Syntax of numpy.where() function
numpy.where
(
condition,
[,
x,
y,
]
)
Example:
import numpy as np
new_arr = np.array([[178, 78, 789], [67, 190, 632]])
output = np.where(new_arr<190)
print(output)
print(new_arr[output])
In the above program, we will use the np.where() function and assign the condition in it. It will check whether the value is present in the array or not. If it is then it will display the index number in the output.
Here is the execution of the following given code
Read: Python NumPy log + Examples
Python numpy empty 2d array
- In this Program, we will discuss how to get 2-dimensional array by using empty function.
- In Python the numpy package provides a function that is numpy.empty() and this method is used to declare a new numpy array of given shapes without initializing entries.
Syntax:
Here is the Syntax of numpy.empty() function
numpy.empty
(
shape,
dtype=float,
order='C',
like=None
)
Example:
import numpy as np
new_arr = np.empty((2, 2, 2))
print(new_arr)
In the above program, we have use the np.empty() function and pass a shape and datatype value in it. Once you will print ‘new_arr’ then the output will display different values that contains in new array.
You can refer to the below Screenshot
Read: Python NumPy square with examples
Python sort 2d numpy array by column
- Here we can see how to sort a 2-dimension array by column in Python.
- In this example, we are going to use the concept of the argsort() method. In Python, this method is used to sort the array along with the given axis of the same shape and this method will always return the indices that would sort the numpy array.
Syntax:
Here is the Syntax of numpy.argsort() function
numpy.argsort
(
a,
axis=-1,
kind=None,
order=None
)
Example:
import numpy as np
new_arr = np.array([[44, 25, 78, 91], [189, 654, 145, 934], [456, 889, 145, 789]])
new_val = 1
new_result = new_arr[new_arr[:,new_val].argsort()]
print(new_result)
In the above code we have sorted numpy array by 2nd column at index 1.
Here is the implementation of the following given code
Read: Python NumPy to list with examples
Python numpy concatenate 2d array
- Let us see how to concatenate a 2-dimension numpy array in Python.
- To perform this particular task we are going to use the numpy.concatenate() function. In Python, this function will help the user for combining or merging 2-d arrays together but in this case, the array should be in the same shape and size along a specified axis.
- This function is available in numpy module and can operate both vertically and horizontally.
Syntax:
Here is the Syntax of numpy.concatenate() function
np.concatenate
(
a1,
a2,
axis=0,
out=None,
dtype=None,
casting="same_kind"
)
Source Code:
import numpy as np
new_arr = np.array([[198, 567, 123], [342, 907, 167]])
new_arr2 = np.array([[745, 567, 234],[782, 567, 190]])
print(np.concatenate((new_arr, new_arr2), axis = -1))
In the above program, we have created two different arrays by using np.array() function and assign integer values in it. Now use concatenate() method for combining two-dimensional arrays.
Here is the execution of the following given code
Read: Python NumPy Average with Examples
Python numpy 2d array to CSV
- Let us see how to save 2-dimensional array with CSV file by using Python.
- In this example, we are going to use np.savetext for performing this task. In Python, this method will help to save a numpy array to a CSV file. This function takes two arguments which are file name and data we can also delimiter in it.
- In this example, the file name ends in CSV mode and the delimiter is used for the CSV file element separator.
Syntax:
Here is the Syntax of numpy.savetxt() method
numpy.savetxt
(
fname,
X,
delimiter='',
newline='\n',
header='',
footer='',
comments='#',
encoding=None
)
Source Code:
CSV file Screenshot
As you can see in the Screenshot the CSV file save the 2-dimensional array.
Read: Python NumPy absolute value with examples
Python numpy 2d array reshape
- Here we can see how to reshape the 2-dimensional array in Python.
- In this example, we can easily use the numpy.reshape() method and this function will shape the array without updating its element. In this program we have to convert a 2-d array to a 1-d array by using the np.reshape() method.
Example:
import numpy as np
new_array1 = np.array([[67, 89, 41, 99],
[45, 77, 23, 45]])
b= new_array1.reshape(new_array1.size,)
print(b)
Here is the Screenshot of the following given code
Python numpy rotate 2d array
- In this section we will discuss how to rotate a 2-dimension array in Python.
- By using the np.rot90() method we can perform this task. This method is used to rotate a numpy array by 90 degrees in the plane axes and the axes will be 0 or 1.
Syntax:
Here is the Syntax of numpy.rot90() method
numpy.rot90
(
m,
k=1,
axes=(0,1)
)
Example:
import numpy as np
new_val = np.array([[89,91], [78,56]])
print(new_val)
result = np.rot90(new_val, 2)
print("After rotating arr:",result)
You can refer to the below Screenshot
Python numpy random 2d array
- In this section we will discuss how to create a 2-dimensional array by using random function in Python.
- In Python the random.rand() function will create a numpy array that is contained with numbers and this module is present in the NumPy module and this function is used to generate random values in a given shape.
- In this example, we have passed (2,2) in an argument that represents the shape and the dimension of a numpy array.
Syntax:
Here is the Syntax of numpy.randm.rand() function
random.rand
(
d0,
d1,
.
.
dn
)
Source Code:
import numpy as np
new_arr = np.random.rand(2,2)
print("Random values for 2d array:",new_arr)
Here is the execution of the following given code
Python numpy 2d array to string
- In this program, we will discuss how to convert 2d-array with string in Python.
- By using the np.array2string() method we can solve this task and this method will always return a string representation of a numpy array.
Syntax:
Here is the Syntax of numpy.array2string() method
numpy.array2string
(
a,
max_line_width=None,
precision=None,
suppress_Small=None,
separator='',
prefix='',
style=<no value>,
formatter=None,
threshold=None,
edgeitems=None,
sign=None,
floatmode=None,
legacy=None
)
Source Code:
import numpy as np
new_arr = np.random.rand(2,2)
b= np.array2string(new_arr, formatter={'float_kind':lambda x: "%.2f" % x})
print(b)
You can refer to the below Screenshot
Python numpy transpose 2d array
- Let us see how to transpose a 2-dimension array in Python.
- In this example, we are going to use the numpy.transpose() method. In Python, this method is used to change the column items into row elements and the row items into column items. This function will always return a new modified array.
- Suppose if the numpy array shape is (m,n) then by using numpy.transpose() method the shape will be (n,m).
Example:
import numpy as np
new_element = np.array([[17,18,13,73,56],[108,23,87,123,84]])
new_output = np.transpose(new_element)
print(new_output)
Here is the implementation of the following given code
As you can see in the Screenshot the output will display a modified numpy array
Python NumPy unique 2d array
- In this section we will discuss how to get the unique values from 2-dimensional array in Python.
- To perform this particular task we are going to use the np.unique() function. In Python this method checks the unique value in an array, for example, we have a 2-d array with repeated values then if we are going to apply the np.unique() function then it will return the unique value.
- This method is available in the numpy module and this function can be able to return a tuple of unique values.
Syntax:
Here is the Syntax of numpy.unique() method
numpy.unique
(
arr,
return_index=False,
return_inverse=False,
return_counts=False,
axis=None
)
Source Code:
import numpy as np
new_array = np.array([[67, 67, 45,92] ,[ 90, 67, 45,11] , [ 20, 67, 45, 67], [67, 67, 45, 67]])
new_result = np.unique(new_array)
print('Unique 2d elements : ', new_result)
In the above program we have created a numpy array by using np.array() function and then use the np.unique() function for getting the unique elements from array.
Here is the Screenshot of the following given code
As you can see in the Screenshot the output will display the unique value which is available in the list.
Python iterate numpy 2d array
- Here we can see how to iterate a numpy 2-dimension array in Python.
- In Python to iterate a 2-dimensional array we can easily use for loop() method in it and for creating a numpy array we can apply the arange() function along with reshape. Once you will print ‘i’ then the output will display the 2-dimensional array.
Example:
import numpy as np
new_arr = np.arange(8).reshape(4,2)
for i in new_arr:
print("Iterating values:",i)
Here is the output of the following given code
Python find index of value in Numpy 2d array
- Let us discuss how to find the index of value in Numpy 2-dimension array by using Python.
- In this example we are going to use the numpy.where() function and this method will check the indices of elements with value ‘934’. If it is present in the given array then it will display the index number.
Source Code:
import numpy as np
new_array = np.array([[78, 95, 34],
[678, 934, 178],
[334, 934, 934],
[334, 554, 678]])
output = np.where(new_array == 934)
print('array value : ',output)
You can refer to the below Screenshot
Python plot numpy 2d array
- In this section we will discuss how to plot a 2-dimension array in Python.
- We have already covered this topic in a numpy 3-d posts. You can refer to this same example in that post but in this example, we have just created a simple 2-dimension array.
Source Code:
import matplotlib.pyplot as plt, numpy as np
from mpl_toolkits.mplot3d import Axes3D
new_arr= np.array([[178,678,345], [234,967,456]])
new_element = plt.figure()
result = new_element.add_subplot(133, projection='2d')
result.plot(new_arr[:,0],new_arr[:,1],new_arr[:,2])
plt.show()
Here is the execution of the following given code
Graph Screenshot
Python numpy argmax 2d array
- Let us see how to find the maximum value in 2-dimension array by using argmax() function.
- In Python the argmax() function returns the indices of the maximum value in an array. This function takes an axis along which you will identify the maximum elements.
Syntax:
Here is the Syntax of numpy.argmax() function
numpy.argmax
(
a,
axis=None,
out=None
)
Example:
import numpy as np
new_arr = np.arange(8).reshape(2, 4)
final_result = np.argmax(new_arr)
print(final_result)
In the above program, we have created a array by using np.arange() function and then apply np.argmax() function for getting the index of maximum value.
Here is the Screenshot of the following given code
Python numpy average 2d array
- In this section we will discuss how to find the average value in 2-dimensional array by using Python.
- To do this task we are going to use the average() function for calculating the average value of the 2-d array. In Python, the average function measures the weighted average of given items in an array and this function has an axis argument and if it is not available then the array is flattened.
Syntax:
Here is the Syntax of numpy.average() function
numpy.average
(
a,
axis=None,
weights=None,
returned=False
)
Example:
import numpy as np
new_arr = np.array([[49, 34,98 ,97],
[85,56,34,15]])
val1 = np.average(new_arr, axis=0)
val1 = np.average(new_arr, axis=1)
print(val1)
You can refer to the below Screenshot
As you can see in the Screenshot the output is average value of 2-d array
Python numpy stack 2d array
- In this program, we will discuss how to stack 2-dimensional array in Python by using stack() method.
- In Python to combine two different numpy arrays, we can also use the np.stack() method and the array must be having the same shape and size.
Syntax:
Here is the syntax of np.stack() method
numpy.stack
(
arrays,
axis=0,
out=None
)
Source Code:
import numpy as np
new_arr = np.array([ 78, 99, 45] )
new_array = np.array([ 34, 91, 20] )
result = np.stack((new_arr, new_array), axis = 0)
print(result)
In the above code we have created two different arrays by using np.array() and then declare a variable ‘result’ in which we have assigned a np.stack() method for combining the arrays.
Here is the execution of the following given code
Python numpy shuffle 2d array
- Let us see how to shuffle a 2-dimension array in Python.
- In this example, we are going to shuffle the elements which are available in a given array by using np.random.shuffle() method.
Syntax:
Here is the Syntax of numpy.random.shuffle() method
random.shuffle(x)
Source Code:
import numpy as np
new_values = np.arange(8).reshape((4, 2))
result =np.random.shuffle(new_values)
print(new_values)
Here is the Screenshot of the following given code
Python numpy filter two-dimensional array by condition
- In this section we will discuss how to filter a 2-dimensional array by condition in Python.
- By using bitwise operators we can filter the array which is based on the condition. In this example we are going to use the numpy greater and less than function in it.
Example:
import numpy as np
new_val = np.array([[89,45,67],
[97,56,45]])
result = np.logical_and(np.greater(new_val, 45), np.less(new_val, 89))
print(new_val[result])
In the above code we have assign a condition if val is greater than 45 than it will display in first and if value is less than 89 than it will display in second index number.
Here is the output of the following given code
Also, read the following tutorials.
- Python NumPy 3d array + Examples
- Python NumPy Data types
- Python NumPy Split + 11 Examples
- Python NumPy Normalize + Examples
In this Python tutorial, we have learned how to use a 2-dimensional NumPy array in Python. Also, we will cover these topics.
- Python NumPy 2d array slicing
- Python NumPy 2d array initialize
- Python NumPy 2d array indexing
- Python NumPy 2d array of zeros
- Python NumPy 2d array to 1d
- Python NumPy 2d array append
- Python NumPy 2d array declaration
- Python NumPy 2d array size
- Python NumPy 2d array to 3d
- Python 2d array without numpy
- Python numpy where 2d array
- Python numpy empty 2d array
- Python sort 2d numpy array by column
- Python numpy concatenate 2d array
- Python numpy 2d array to CSV
- Python numpy 2d array reshape
- Python numpy rotate 2d array
- Python numpy random 2d array
- Python numpy 2d array to string
- Python numpy transpose 2d array
- Python NumPy unique 2d array
- Python iterate numpy 2d array
- Python numpy 2d array of zeros
- Python find index of value in Numpy 2d array
- Python plot numpy 2d array
- Python numpy argmax 2d array
- Python numpy average 2d array
- Python numpy stack 2d array
- Python numpy shuffle 2d array
- Python numpy filter two dimensional array by condition
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.