0% found this document useful (0 votes)
7 views13 pages

Numpyprogram 3

The document provides an overview of NumPy arrays, detailing their properties such as shape, length, dimensions, and data types. It explains how to reshape arrays, flatten them, and convert data types using methods like reshape() and astype(). Additionally, it includes examples demonstrating the use of these features in Python code.

Uploaded by

ganchirekha6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views13 pages

Numpyprogram 3

The document provides an overview of NumPy arrays, detailing their properties such as shape, length, dimensions, and data types. It explains how to reshape arrays, flatten them, and convert data types using methods like reshape() and astype(). Additionally, it includes examples demonstrating the use of these features in Python code.

Uploaded by

ganchirekha6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link]([Link],len(array),array.

ndim,arr
[Link],[Link](type),type(array))
[Link]
[Link]
the dimensions of the array. This is a tuple of integers indicating the
size of the array in each dimension. For a matrix with n rows
and m columns, shape will be (n,m). The length of the shape tuple
is therefore the number of axes, ndim.

The shape of an array is the number of elements in each dimension.


NumPy arrays have an attribute called shape that returns a tuple with each
index having the number of corresponding elements.

Print the shape of a 2-D array:

import numpy as np

arr = [Link]([[1, 2, 3, 4], [5, 6, 7, 8]])

print([Link])

output
(2, 4)

import numpy as np

arr = [Link]([1, 2, 3, 4], ndmin=5)

print(arr)

print('shape of array :', [Link])

output
[[[[[1 2 3 4]]]]]

shape of array : (1, 1, 1, 1, 4)

import numpy as np

arr = [Link]([1, 2, 3, 4, 5])

print([Link])

output
(5,)

Reshaping arrays
Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of


elements in each dimension.

Reshape From 1-D to 2-D


ExampleGet your own Python Server
Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = [Link](4, 3)

print(newarr)

[[ 1 2 3]

[ 4 5 6]

[ 7 8 9]
[10 11 12]]

Reshape From 1-D to 3-D


Example
Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with
2 elements:

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = [Link](2, 3, 2)

print(newarr)

output

[[[ 1 2]

[ 3 4]

[ 5 6]]

[[ 7 8]

[ 9 10]

[11 12]]]

Example
Try converting 1D array with 8 elements to a 2D array with 3 elements in
each dimension (will raise an error):

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])

newarr = [Link](3, 3)

print(newarr)
output
Traceback (most recent call last):

File "E:/[Link]", line 5, in <module>

newarr = [Link](3, 3)

ValueError: cannot reshape array of size 8 into shape (3,3)

Unknown Dimension
You are allowed to have one "unknown" dimension.

Meaning that you do not have to specify an exact number for one of the
dimensions in the reshape method.

Pass -1 as the value, and NumPy will calculate this number for you.

Example
Convert 1D array with 8 elements to 3D array with 2x2 elements:

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])

newarr = [Link](2, 2, -1)

print(newarr)

output:
[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Flattening the arrays


Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.


Example
Convert the array into a 1D array:

import numpy as np

arr = [Link]([[1, 2, 3], [4, 5, 6]])

newarr = [Link](-1)

print(newarr)

output:
[1 2 3 4 5 6]

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](4, 3)
print(newarr)

output
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

LEN(ARRAY)
Array Length in Python using the len() method
Python has a len() method to find out the length of an array. The syntax is as follows:

len(arr)
Example
import numpy as np

arr = [Link]([1,6,3,7,1])
print("Elements in the array: ", arr)
print("Length of the array: ", len(arr))

Output

Elements in the array: [1 6 3 7 1]

Length of the array: 5

Finding the Length of a Python NumPy Array


Numpy is a library compatible with Python for operating complex mathematical operations
on multi-dimensional arrays. We use numpy for mathematical operations on arrays. Here is
how we can find the length of an array in Python using numpy:

Example

import numpy as np

arr = [Link]([1,6,3,7,1])
print("Elements in the array: ", arr)
print("Length of the array: ", len(arr))

Output

Elements in the array: [1 6 3 7 1]


Length of the array: 5

import numpy

counts = [Link]([10, 20, 30, 40, 50, 60, 70, 80])

if len(counts) > 5:

print("This array meets the minimum length requirement.")

else:

print("This array is too short!")

outpur

This array meets the minimum length requirement.

import numpy

counts = [Link]([10, 20, 30, 40, 50, 60, 70, 80])

memory_in_bytes = [Link] * len(counts)

print("This array uses", memory_in_bytes, "bytes.")


output
This array uses 32 bytes.

Calculating Lengths of Strings


Using len() with a list that makes up a string will reveal the number of
characters that make up the string. Strings, just like lists, are a collection
of items. Therefore, a string’s length is equal to the number of characters
within. Take a look at how this works:

phrase = "Hello, World!"

print("This phrase contains", len(phrase), "characters.")

output
This phrase contains 13 characters.

[Link]
[Link]() method | Python
[Link]() function return the number of dimensions of
an array.
Syntax : [Link](arr)
Parameters :
arr : [array_like] Input array. If it is not already an ndarray, a
conversion is attempted.
Return : [int] Return the number of dimensions in arr.

import numpy as geek


arr = [Link]([1, 2, 3, 4])
gfg = [Link]
print (gfg)
Output :
1

import numpy as geek

arr = [[1, 2, 3], [4, 5, 6]]

gfg = [Link](arr)

print (gfg)

output
2

[Link]
Data Types in Python
By default Python have these data types:

 strings - used to represent text data, the text is given under quote
marks. e.g. "ABCD"
 integer - used to represent integer numbers. e.g. -1, -2, -3
 float - used to represent real numbers. e.g. 1.2, 42.42
 boolean - used to represent True or False.
 complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 +
2.5j

Data Types in NumPy


NumPy has some extra data types, and refer to data types with one
character, like i for integers, u for unsigned integers etc.

Below is a list of all data types in NumPy and the characters used to
represent them.

 i - integer
 b - boolean
 u - unsigned integer
 f - float
 c - complex float
 m - timedelta
 M - datetime
 O - object
 S - string
 U - unicode string
 V - fixed chunk of memory for other type ( void )

Checking the Data Type of an Array


The NumPy array object has a property called dtype that returns the data
type of the array:

Example

import numpy as np

arr = [Link]([1, 2, 3, 4])

print([Link])

output
int32

import numpy as np

arr = [Link](['apple', 'banana', 'cherry'])

print([Link])

output
<U6

import numpy as np
arr = [Link]([1, 2, 3, 4], dtype='S')
print(arr)
print([Link])
[b'1' b'2' b'3' b'4']
output
|S1

import numpy as np

arr = [Link]([1, 2, 3, 4], dtype='i4')

print(arr)
print([Link])

output
[1 2 3 4]
int32

What if a Value Can Not Be


Converted?
If a type is given in which elements can't be casted then NumPy will raise a
ValueError.

ValueError: In Python ValueError is raised when the type of passed


argument to a function is unexpected/incorrect.

Example
A non integer string like 'a' can not be converted to integer (will raise an
error):

import numpy as np

arr = [Link](['a', '2', '3'], dtype='i')


out put
Traceback (most recent call last):
File "./[Link]", line 3, in <module>
ValueError: invalid literal for int() with base 10: 'a'
[Link](TYPE)
Converting Data Type on Existing
Arrays
The best way to change the data type of an existing array, is to make a copy
of the array with the astype() method.

The astype() function creates a copy of the array, and allows you to specify
the data type as a parameter.

The data type can be specified using a string, like 'f' for float, 'i' for integer
etc. or you can use the data type directly like float for float and int for
integer.

Example
Change data type from float to integer by using 'i' as parameter value:

import numpy as np

arr = [Link]([1.1, 2.1, 3.1])

newarr = [Link]('i')

print(newarr)
print([Link])

output
[1 2 3]
int32

Example
Change data type from float to integer by using int as parameter value:

import numpy as np

arr = [Link]([1.1, 2.1, 3.1])

newarr = [Link](int)
print(newarr)
print([Link])

output
[1 2 3]
int32

Example
Change data type from integer to boolean:

import numpy as np

arr = [Link]([1, 0, 3])

newarr = [Link](bool)

print(newarr)
print([Link])

output
[ True False True]
Bool

TYPE(ARRAY)
# Python program to differentiate
# between type and dtype.
import numpy as np

a = [Link]([1])

print("type is: ",type(a))


print("dtype is: ",[Link])

OUTPUT
type is: <class '[Link]'>
dtype is: int32

You might also like