0% found this document useful (0 votes)
113 views

Write A Numpy Program To Reverse An Array (First Element Becomes Last)

This document contains code snippets demonstrating various NumPy array operations and functions including: 1. Creating 1D, 2D, and 3D NumPy arrays and printing their attributes. 2. Extracting specific elements, columns, rows from NumPy arrays. 3. Reversing, padding, and modifying NumPy arrays. 4. Creating arrays with checkerboard patterns and from ranges with specified differences between elements. It provides examples of common NumPy array manipulation tasks like slicing, indexing, reshaping, and extracting subsets of arrays.

Uploaded by

Wodari Helena
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)
113 views

Write A Numpy Program To Reverse An Array (First Element Becomes Last)

This document contains code snippets demonstrating various NumPy array operations and functions including: 1. Creating 1D, 2D, and 3D NumPy arrays and printing their attributes. 2. Extracting specific elements, columns, rows from NumPy arrays. 3. Reversing, padding, and modifying NumPy arrays. 4. Creating arrays with checkerboard patterns and from ranges with specified differences between elements. It provides examples of common NumPy array manipulation tasks like slicing, indexing, reshaping, and extracting subsets of arrays.

Uploaded by

Wodari Helena
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
You are on page 1/ 8

import numpy as np

arr=np.array([])

Extract odd: arr[arr%2==1]


Extract odd: arr[arr%2==0]

Write a NumPy program to reverse an array (first element becomes last)


Type-1:
arr=arr[::-1] //[start:end:step]
print(arr)

Type-2:
arr=np.flip(arr)
print(arr)

Add a border (filled with 0's) around an existing array


arr=np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
arr=np.pad(arr,pad_width=1,mode='constant',constant_values=0)
print(arr)

Write a NumPy program to create a 8x8 matrix and fill it with a checkerboard
pattern. (0 1 0 1 0 1 0 1 )
x = np.zeros((8,8),dtype=int)
x[1::2,::2] = 1
x[::2,1::2] = 1
print(x)

Check a number is even or odd by selected number of operation


a=int(input())
for i in range(a):
num = int(input())
if num >=1 and num <=100:
if num%2==0:
print("even")
else:
print("odd")
else:
print("Enter a number between 1 to 100")

Format a float
a = 2.154327
format_float = "{:.2f}".format(a)
print(format_float)
#Q.Write a Program to find the sum of all numbers stored in a list
//Type-1
num = [1, 2, 3, 4, 5]
sum = 0
for x in num:
sum += x
print(sum)

//Type-2
n=[2,3,4,5,6,7]
sum=0
i=0
while i < len(n):
sum+=n[i]
i+=1
print(sum)

appending item through function:


def changeme(mylist ):
mylist.append(1);
print ("Values inside the function: ", mylist)
return

mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)

appending name:
def my_function(fname):
print(fname + " Zaman")
my_function("Mina")
my_function("Farhim")
my_function("Tina")

String:
data = "I lovee data science"
type(data)
len(data)

import sys
sys.getsizeof(data)

data.count("data")
data.find("data")
data.find('v')
data.find("v",6,10)
data.index('v')
data.index("w")
data.upper()
data.lower()
data.capitalize()
data.swapcase()
data.title()
data.split()
data.split()[1]
data.replace('data','ai')

//list
n = [1,2,3,"ritu",True,(1,2,3)]
n[0:4]/// n[-1]/// n[-1][0]
list element update: list[2]=2000;
list element delete: del(list[2])
n = [1,2,3,"ritu","nil",True,(1,2,3)]
n[0:4] -_--> [1, 2, 3, 'ritu']

//tuple
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5]) - (2, 3, 4, 5)
tup3 = tup1 + tup2;
print (tup3)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
print(dict)

student_name = 'Sobuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')

#numpy array 1D
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

#2D
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

#3D
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)

np.zeros((3,4))
np.ones((3,4))
Reverse the tuple
tuple1 = (10, 20, 30, 40, 50)
tuple1 = tuple1[::-1]
print(tuple1)

Access value 20 from the tuple


tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))
prit(tuple1[1][1])

Create a tuple with single item 50


tuple1= (50, )
print(tuple1)

Unpack the tuple into 4 variables


tuple1 = (10, 20, 30, 40)

# unpack tuple into 4 variables


a, b, c, d = tuple1
print(a)
print(b)
print(c)
print(d)

Swap two tuples in Python


tuple1 = (11, 22)
tuple2 = (99, 88)
tuple1, tuple2 = tuple2, tuple1
print(tuple2)
print(tuple1)

Copy specific elements from one tuple to a new tuple


tuple1 = (11, 22, 33, 44, 55, 66)
tuple2 = tuple1[3:-1]
print(tuple2)

Modify the tuple


tuple1 = (11, [22, 33], 44, 55)
tuple1[1][0] = 222
print(tuple1)

Sort a tuple of tuples by 2nd item


tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29))
tuple1 = tuple(sorted(list(tuple1), key=lambda x: x[1]))
print(tuple1)

Exercise 9: Counts the number of occurrences of item


50 from a tuple
tuple1 = (50, 10, 60, 70, 50)
print(tuple1.count(50))

Check if all items in the tuple are the same


def check(t):
return all(i == t[0] for i in t)

tuple1 = (45, 45, 45, 45)


print(check(tuple1))

Create a 4X2 integer array and Prints its attributes

import numpy

firstArray = numpy.empty([4,2], dtype = numpy.uint16)


print("Printing Array")
print(firstArray)

print("Printing numpy array Attributes")


print("1> Array Shape is: ", firstArray.shape)
print("2>. Array dimensions are ", firstArray.ndim)
print("3>. Length of each element of array in bytes is ",
firstArray.itemsize)

Create a 5X2 integer array from a range between 100 to 200 such that
the difference between each element is 10

import numpy

print("Creating 5X2 array using numpy.arange")


sampleArray = numpy.arange(100, 200, 10)
sampleArray = sampleArray.reshape(5,2)
print (sampleArray)

Following is the provided numPy array. Return array of items by taking


the third column from all rows

import numpy
sampleArray = numpy.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])
print("Printing Input Array")
print(sampleArray)

print("\n Printing array of items in the third column from all rows")
newArray = sampleArray[...,2]
print(newArray)

Return array of odd rows and even columns from below numpy array

import numpy

sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24],


[27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])
print("Printing Input Array")
print(sampleArray)

print("\n Printing array of odd rows and even columns")


newArray = sampleArray[::2, 1::2]
print(newArray)

You might also like