NumPy - Arrays - Practice Problems #21
Replies: 15 comments
-
1.- import numpy as np
print(np.array([12.23, 13.32, 100, 36.32])) 2.- import numpy as np
print(np.arange(2, 11).reshape(3, 3)) 3.- import numpy as np
array = np.zeros(10)
array [6] = 11
print(array) 4.- import numpy as np
array = np.arange(12, 38)
array = array[::-1]
print(array) 5.- import numpy as np
thetuple = ([5, 5, 6], [9, 6, 3], [23, 43, 23])
print(np.asarray(thetuple)) 6.- import numpy as np
fanrenheit = np.array([0, 12, 45.21, 34, 99.91, 32])
print("Centigrade degrees: ",np.round((5*fanrenheit/9 - 5*32/9), 2))
centigrade = np.array([-17.78, -11.11, 7.34, 1.11, 37.73, 0])
print("Fahrenheit degrees: ",np.round((9*centigrade/5 + 32),2)) 7.- import numpy as np
num1 = np.sqrt([1+0j])
num2 = np.sqrt([0+1j])
print("Real:")
print(num1.real, " ", num2.real)
print("Imaginary:")
print(num1.imag, " ", num2.imag) 8.- import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
array2 = [0, 40]
print(np.in1d(array1, array2)) 9.- import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
array2 = [10, 40, 60]
print(np.intersect1d(array1, array2)) 10.- import numpy as np
array1 = np.array([10, 10, 20, 20, 30, 30])
array2 = np.array([[1, 1], [2, 3]])
print(np.unique(array1))
print(np.unique(array2)) 11.- import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
array2 = [10, 30, 40, 50, 70]
print(np.setdiff1d(array1, array2)) 12.- import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
array2 = [10, 30, 40, 50, 70]
print(np.setxor1d(array1, array2)) 13.- import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
array2 = [10, 30, 40, 50, 70]
print(np.union1d(array1, array2)) 14.- import numpy as np
x = np.array([1, 2])
y = np.array([4, 5])
print(np.greater(x, y))
print(np.greater_equal(x, y))
print(np.less(x, y))
print(np.less_equal(x, y)) 15.- import numpy as np
x = np.array([[4, 6],[2, 1]])
print(np.sort(x, axis=0))
print(np.sort(x, axis=1)) 16.- import numpy as np
Fnames = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
Lnames = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
print(np.lexsort((Fnames, Lnames))) 17.- import numpy as np
array = np.array([[0, 10, 20], [20, 30, 40]])
print(array[array>10])
print(np.nonzero(array > 10)) 18.- import numpy as np
array = np.array([[10, 20, 30], [20, 40, 50]])
print(np.ravel(array)) 19.- import numpy as np
array1=np.array([1,2,3,4])
array2=np.array(['Red','Green','White','Orange'])
array3=np.array([12.20,15,20,40])
newarray = np.core.records.fromarrays([array1, array2, array3])
print(newarray) 20.- import numpy as np
array1=np.array([[0,1],[2,3],[4, 5]])
print(array1.tolist()) 21.- import numpy as np
array1 = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
array1[array1< 0] = 0
print(array1) 22.- import numpy as np
array1 = np.array([[1, 2, 3], [4, 5, np.nan], [7, 8, 9], [True, False, True]])
print(array1[~np.isnan(array1).any(axis=1)]) 23.- import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print(b[(100 < a) & (a < 110)]) 24.- import numpy as np
array = np.array([10,10,20,10,20,20,20,30,30,50,40,40])
unique, count = np.unique(array, return_counts=True)
print(np.asarray((unique, count))) 25.- import numpy as np
array = np.array([10, 20, 30])
print(array.sum())
print(array.prod()) |
Beta Was this translation helpful? Give feedback.
-
1. List to 1-D array# list to 1D array
import numpy as np
def main():
lst = [np.random.randint(0,10) for _ in range(10)]
print(f"List: {lst}")
print(f"1-Dimensional array: {np.array(lst)}")
if __name__ == "__main__":
main() 2. 3x3 matrix with values from 2 to 10# 3x3 matrix 2-10 vals
import numpy as np
def main():
mat = np.arange(2,11)
mat = mat.reshape(3,3)
print(f"3x3 matrix: \n{mat}")
if __name__ == "__main__":
main() 3. Null vector of size 10# vector
import numpy as np
def main():
vec = np.zeros(10)
vec[6] = 11
print(f"Vector: \n{vec}")
if __name__ == "__main__":
main() 4. Reverse array# reverse array (using matrix operations)
import numpy as np
def main():
vec = np.random.randint(1,100,10)
print(f"Orignal Array: \n{vec}")
print(f"Reversed Array: \n{np.flip(vec)}")
if __name__ == "__main__":
main() 5. Convert list and tuple to array# list and tuple to array
import numpy as np
def main():
lst = [np.random.randint(10) for _ in range(4)]
tuple = ((1,2,3),(0,3,6),(3,123,10))
print(f"Orignal List: \n{lst}")
print(f"List to Array: \n{np.array(lst)}")
print(f"Orignal Tuple: \n{tuple}")
print(f"Tuple to Array: \n{np.array(tuple)}")
if __name__ == "__main__":
main() 6. Celsius into Fahrenheit and vice versa# celsius to Fahrenheit
import numpy as np
def fahToC(array):
return ((5*array/9)-32*5/9)
def celToF(array):
return ((array*9/5)+32)
def main():
tempF = np.array([0, 12, 45.21, 34, 99.91])
tempC = np.array([-17.78, -11.11, 7.34, 1.11, 37.73, 0. ])
print(f"Original Fahrenheit temperatures: \n{tempF}")
print(f"Fahrenheit to Celsius temperatures: \n{fahToC(tempF)}")
print(f"Original Celsius temperatures: \n{tempC}")
print(f"Celsius to Fahrenheit temperatures: \n{celToF(tempC)}")
if __name__ == "__main__":
main() 7. Real and Imaginary parts of complex array# real and imaginary in complex
import numpy as np
def main():
complexA = np.array([1+0.5j,-2+4j,2,10j])
print(f"Original Array: \n{complexA}")
print(f"Real parts of Array: \n{complexA.real}")
print(f"Imaginary parts of Array: \n{complexA.imag}")
if __name__ == "__main__":
main() 8. Elements in Array 1 in Array 2# is in
import numpy as np
def main():
A = np.arange(10)
B = np.arange(1,10,2)
print(f"Original Array A: \n{A}")
print(f"Original Array B: \n{B}")
print(f"Elements of A in B: \n{np.isin(A,B)}")
if __name__ == "__main__":
main() 9. Common values between two arrays# set intersection
import numpy as np
def main():
A = np.arange(10)
B = np.arange(2,15,2)
print(f"Original Array A: \n{A}")
print(f"Original Array B: \n{B}")
print(f"Common elements in A and B: \n{np.intersect1d(A,B)}")
if __name__ == "__main__":
main() 10. Unique elements in array# set unique
import numpy as np
def main():
A = np.array([1,2,2,3,4,5,4,6,5,1,2,3,1,2,2])
# B = np.arange(2,15,2)
print(f"Original Array A: \n{A}")
# print(f"Original Array B: \n{B}")
print(f"Unique elements in A: \n{np.unique(A)}")
if __name__ == "__main__":
main() 11. Set difference# set intersection
import numpy as np
def main():
A = np.arange(1,10)
B = np.arange(2,15,2)
print(f"Original Array A: \n{A}")
print(f"Original Array B: \n{B}")
print(f"Different elements of A in B: \n{np.setdiff1d(A,B)}")
if __name__ == "__main__":
main() 12. Set exclusive# set exlcusive (xor)
import numpy as np
def main():
A = np.arange(1,10)
B = np.arange(2,15,2)
print(f"Original Array A: \n{A}")
print(f"Original Array B: \n{B}")
print(f"Exclusive elements of A and B: \n{np.setxor1d(A,B)}")
if __name__ == "__main__":
main() 13. Set union# set union
import numpy as np
def main():
A = np.arange(1,10)
B = np.arange(2,15,2)
print(f"Original Array A: \n{A}")
print(f"Original Array B: \n{B}")
print(f"Union of A and B: \n{np.union1d(A,B)}")
if __name__ == "__main__":
main() 14. Comparison (>,>=,<,<=)# comparissons >,>=,<=,<=
import numpy as np
def main():
A = np.random.randint(1,15,5)
B = np.random.randint(1,15,5)
print(f"Original Array A: \n{A}")
print(f"Original Array B: \n{B}")
print(f"A > B: \n{A>B}")
print(f"A >= B: \n{A>=B}")
print(f"A < B: \n{A<B}")
print(f"A <= B: \n{A<=B}")
if __name__ == "__main__":
main() 15. Sort array (first and last axis)# sorting by axis
import numpy as np
def main():
A = np.random.randint(1,15,9).reshape(3,3)
print(f"Original Array A: \n{A}")
# print(f"Original Array B: \n{B}")
print(f"Sorted by first axis: \n{np.sort(A,axis=0)}")
print(f"Sorted by second axis: \n{np.sort(A,axis=1)}")
if __name__ == "__main__":
main() 16. Indices of sorted pairs# sorting by array
import numpy as np
def main():
# A = np.random.randint(1,15,9).reshape(3,3)
first_names = ["Betsey", "Shelley", "Lanell", "Genesis", "Margery"]
last_names = ["Battle", "Brien", "Plotner", "Stahl", "Woolum"]
print(f"Original first names: \n{first_names}")
print(f"Original last names: \n{last_names}")
print(f"Index of sorted: \n{np.lexsort((last_names,first_names))}")
if __name__ == "__main__":
main() 17. Value and index of elements > 10# values >10 and indices
import numpy as np
def main():
A = np.random.randint(1,15,9).reshape(3,3)
print(f"Original array: \n{A}")
print(f"Values bigger than 10: \n{A[A>10]}")
print(f"Indices of values > 10: \n{np.nonzero(A>10)}")
if __name__ == "__main__":
main() 18. Contiguous flattened array# flattened array
import numpy as np
def main():
A = np.random.randint(1,15,9).reshape(3,3)
print(f"Original array: \n{A}")
print(f"Flattened array: \n{A.flatten()}")
if __name__ == "__main__":
main() 19. Record array from lists# array array
import numpy as np
def main():
# A = np.random.randint(1,15,9).reshape(3,3)
A = [1,2,3,4]
B = ['Red', 'Green', 'White', 'Orange']
C = [12.20,15,20,40]
view = np.core.records.fromarrays([A, B, C],names='a,b,c')
print(f"Original arrays: \n{A,B,C}")
print(f"Record array: \n{view}")
if __name__ == "__main__":
main() 20. Array into List# array to list
import numpy as np
def main():
A = np.random.randint(1,15,9).reshape(3,3)
print(f"Original array: \n{A} {type(A)}")
print(f"Array as List: \n{A.tolist()} {type(A.tolist())}")
if __name__ == "__main__":
main() 21. Replace negatives with 0 in array# array to list
import numpy as np
def main():
A = np.random.randint(-10,10,9).reshape(3,3)
print(f"Original array: \n{A}")
#replace negatives
A[A<0] = 0
print(f"Array with negatives replaced with 0: \n{A}")
if __name__ == "__main__":
main() 22. Remove rows with non-numeric# replace non.numeric
import numpy as np
def main():
A = np.random.randn(9).reshape(3,3)
# place non-numeric value in array
A[0,0] = np.nan
print(f"Original array: \n{A}")
# remove rows with non-numeric using '~' as not
A = A[~np.any(np.isnan(A),axis=1)]
print(f"Array with non-numeric rows removed: \n{A}")
if __name__ == "__main__":
main() 23. Select from array with multiple conditions# select with multiple conditions
import numpy as np
def main():
A = np.random.randint(90,110,5)
B = np.array(['a','e','i','o','u'])
print(f"Original array A: \n{A}")
print(f"Original array B: \n{B}")
# find index where A > 100
print(f"Values of B where A > 100: \n{B[A>100]}")
if __name__ == "__main__":
main() 24. Frequency of unique values# count unique
import numpy as np
def main():
A = np.random.randint(1,6,15)
print(f"Original array A: \n{A}")
# count unique value occurrences
unique,count = np.unique(A, return_counts=True)
print(f"Values of B where A > 100: \n{unique}")
print(f"Frequency of unique values: \n{count}")
if __name__ == "__main__":
main() 25. Sum and Product of arrays# internal sum and product
import numpy as np
def main():
A = np.random.randint(10,50,4)
print(f"Original array A: \n{A}")
print(f"Sum of A: \n{np.sum(A)}")
print(f"Product of A: \n{np.product(A)}")
if __name__ == "__main__":
main() |
Beta Was this translation helpful? Give feedback.
-
import numpy as np
originalList = [12.12, 13.13, 111, 35.24]
arr = np.array(originalList)
print(arr) import numpy as np
arr = np.arange(2, 11).reshape(3,3)
print(arr) import numpy as np
arr = np.zeros(10)
arr[6] = 11
print(arr) import numpy as np
arr = np.arange(1,10)
arr = np.flip(arr)
print(arr) import numpy as np
tup = ([1, 2, 3], [4, 5, 6], [7, 8, 9])
print(np.asarray(tup)) import numpy as np
far = np.array([0.12, 45.21, 34, 99.1, 32])
print(f"Fahrenheit to celsius {np.round((far-32)*(5/9))}")
cel = np.array([-18, 27, 16, 81.32, 14.22])
print(f"Celsius to Fahrenheit {cel*(9/5)+32}") import numpy as np
arr = np.array([ 1.00000000+0.j, 0.70710678+0.70710678j])
print(f"Real {arr.real}")
print(f"Imaginary {arr.imag}") import numpy as np
arr = np.array([0, 10, 20, 40, 60])
arr2 = np.array([0, 40])
print(np.isin(arr,arr2)) import numpy as np
arr = np.array([0, 10, 20, 40, 60])
arr2 = np.array([0, 40])
print(np.intersect1d(arr,arr2)) import numpy as np
arr = np.array([0, 10, 20, 40, 60, 10, 20, 40, 60, 0])
print(np.unique(arr)) import numpy as np
arr2 = np.array([0, 10, 20, 40, 60, 10, 20, 40, 60, 0])
arr = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
print(np.setdiff1d(arr, arr2)) import numpy as np
arr2 = np.array([0, 10, 20, 40, 60, 10, 20, 40, 60, 0])
arr = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
print(np.setxor1d(arr, arr2)) import numpy as np
arr2 = np.array([0, 10, 20, 40, 60, 10, 20, 40, 60, 0])
arr = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
print(np.union1d(arr, arr2)) import numpy as np
arr = np.array([0, 10, 20, 30, 40])
arr2 = np.array([0, 10, 20, 40, 60])
print(f" a > b {np.greater(arr, arr2)}")
print(f" a >= b {np.greater_equal(arr, arr2)}")
print(f" a < b {np.less(arr, arr2)}")
print(f" a <= b {np.less_equal(arr, arr2)}") import numpy as np
arr = np.array([[4, 6], [2, 1]])
print(f"original array \n{arr}")
print(f"sort along first axis \n{np.sort(arr, axis=0)}")
print(f"sort along last axis\n{np.sort(arr, axis=1)}") import numpy as np
firstNames = ("Betsy", "Shelley", "Lanell", "Genesis", "Margery")
lastNames = ("Battle", "Brien", "Plotner", "Stahl", "Woolum")
print(np.lexsort((lastNames, firstNames))) import numpy as np
arr = np.array([0, 10, 20, 30, 40])
print(np.nonzero(arr > 10)) import numpy as np
arr = np.array([[0, 10], [30, 40]])
print(f"original arr {arr}")
print(f"Flat arr {arr.reshape(1,arr.size)}") import numpy as np
arr = np.array([1, 2, 3, 4])
arr2 = np.array(["red", "green", "white", "orange"])
arr3 = np.array([12.2, 15, 20, 40])
combined = np.core.records.fromarrays([arr, arr2, arr3])
print(combined) import numpy as np
arr = np.array([[1, 2], [3, 4]])
arrList = arr.tolist()
print(arrList) import numpy as np
arr = np.array([1, 23, 4, -1, -2, 25])
print(f"Original Array \n{arr}\n")
arr[arr < 0]= 0
print(f"Replace negative with 0\n {arr}") import numpy as np
arr = np.array([[1, 23, np.nan], [5, -2, 25]])
print(arr[~np.isnan(arr).any(axis=1)]) import numpy as np
arr = np.array([97, 101, 105, 111, 117])
arr2 = np.array(['a', 'e', 'i', 'o', 'u'])
print(arr2[(100 < arr) & (arr < 110)]) import numpy as np
arr = np.array([97, 101, 105, 111, 117, 97, 101, 105, 105])
unique, count = np.unique(arr, return_counts=True)
print(np.asarray((unique, count))) import numpy as np
arr = np.array([97, 101, 105, 111, 117, 97, 101, 105, 105])
print(np.sum(arr))
print(np.prod(arr)) |
Beta Was this translation helpful? Give feedback.
-
#1.Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array. import numpy as np
l = [12.23, 13.32, 100, 36.32]
print("Original List:",l)
a = np.array(l)
print("One-dimensional NumPy array: ",a) 2.Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10. import numpy as np
x = np.arange(2, 11).reshape(3,3)
print(x) 3.Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10. import numpy as np
x = np.zeros(10)
print(x)
print("Update sixth value to 11")
x[6] = 11
print(x) 4.Write a NumPy program to reverse an array (the first element becomes the last). import numpy as np
x = np.arange(12, 38)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x) 5.Write a NumPy program to convert a list and tuple into arrays. import numpy as np
list = [1, 2, 3, 4, 5, 6, 7, 8]
print("list to array")
print(np.asarray(list))
tuple = [[8, 4, 2],[1, 2, 3]]
print("tuple to array")
print(np.asarray(tuple)) import numpy as np
fvalues = [0, 12, 45.21, 34, 99.91, 32]
F = np.array(fvalues)
print("Values in Fahrenheit degrees:")
print(F)
print("Values in Centigrade degrees:")
print(np.round((5*F/9 - 5*32/9),2)) 7.Write a NumPy program to find the real and imaginary parts of an array of complex numbers. import numpy as np
fvalues = [0, 12, 45.21, 34, 99.91, 32]
F = np.array(fvalues)
print("Values in Fahrenheit degrees:")
print(F)
print("Values in Centigrade degrees:")
print(np.round((5*F/9 - 5*32/9),2)) 8.Write a NumPy program to test whether each element of a 1-D array is also present in a second array. import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [0, 40]
print("Array2: ",array2)
print("Compare each element of array1 and array2")
print(np.in1d(array1, array2)) 9.Write a NumPy program to find common values between two arrays. import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2)) 10 import numpy as np
x = np.array([10, 10, 20, 20, 30, 30])
print("Original array:")
print(x)
print("Unique elements of the above array:")
print(np.unique(x))
x = np.array([[1, 1], [2, 3]])
print("Original array:")
print(x)
print("Unique elements of the above array:")
print(np.unique(x)) import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
print("Array1: ",array1)
array2 = [10, 30, 40, 50, 70]
print("Array2: ",array2)
print("Unique values in array1 that are not in array2:")
print(np.setdiff1d(array1, array2)) 12.Write a NumPy program to find the set exclusive-or of two arrays. Set exclusive-or will return the sorted, unique values in only one (not both) of the input arrays. import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
print("Array1: ",array1)
array2 = [10, 30, 40, 50, 70]
print("Array2: ",array2)
print("Unique values that are in only one (not both) of the input arrays:")
print(np.setxor1d(array1, array2)) 13.Write a NumPy program to find the union of two arrays. Union will return the unique, sorted array of values in either of the two input arrays. import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
print("Array1: ",array1)
array2 = [10, 30, 40, 50, 70]
print("Array2: ",array2)
print("Unique sorted array of values that are in either of the two input arrays:")
print(np.union1d(array1, array2)) 14.Write a NumPy program comparing two given arrays. import numpy as np
A = np.array([[1, 1], [2, 2]])
B = np.array([[1, 1], [2, 2]])
equal_arrays = (A == B).all()
print(equal_arrays)
15.Write a NumPy program to sort along the first, and last axis of an array. import numpy as np
a = np.array([[4, 6],[2, 1]])
print("Original array: ")
print(a)
print("Sort along the first axis: ")
x = np.sort(a, axis=0)
print(x)
print("Sort along the last axis: ")
y = np.sort(x, axis=1)
print(y) 16 import numpy as np
first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
x = np.lexsort((first_names, last_names))
print(x) import numpy as np
arr = np.array([0, 10, 20, 30, 40])
print(np.nonzero(arr > 10)) 18 import numpy as np
array = np.array([[10, 20, 30], [20, 40, 50]])
print(np.ravel(array))
import numpy as np
arr = np.array([1, 2, 3, 4])
arr2 = np.array(["red", "green", "white", "orange"])
arr3 = np.array([12.2, 15, 20, 40])
combined = np.core.records.fromarrays([arr, arr2, arr3])
print(combined) import numpy as np
def main():
a = np.arange(6).reshape(3, 2)
print("Orginals:\n", a)
print("Array to list:\n", a.tolist())
if __name__ == '__main__': main()
21. import numpy as np
x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
print("Original array:")
print(x)
print("Replace the negative values of the said array with 0:")
x[x < 0] = 0
print(x) import numpy as np
x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]])
print("Original array:")
print(x)
print("Remove all non-numeric elements of the said array")
print(x[~np.isnan(x).any(axis=1)]) import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print(b[(100 < a) & (a < 110)]) 24 import numpy as np
def main():
A = np.random.randint(1,6,15)
print(f"Original array A: \n{A}")
# count unique value occurrences
unique,count = np.unique(A, return_counts=True)
print(f"Values of B where A > 100: \n{unique}")
print(f"Frequency of unique values: \n{count}")
if __name__ == "__main__":
main() import numpy as np
x = np.array([10, 20, 30], float)
print("Original array:")
print(x)
print("Sum of the array elements:")
print(x.sum())
print("Product of the array elements:")
print(x.prod())
|
Beta Was this translation helpful? Give feedback.
-
Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array. import numpy as np
list = [12.23, 13.32, 100., 36.32]
nparr = np.array(list)
print("Original list: ",list)
print("One dimensional numpy array: ",nparr) Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10. import numpy as np
nparr = np.arange(2,10+1).reshape(3,3)
print("NumPyArray:\n",nparr) Write a NumPy program to create a null vector of size 10 and update the sixth value to 11. import numpy as np
nparr = np.zeros(10)
print(nparr)
nparr[5] = 11
print(nparr) Write a NumPy program to reverse an array (the first element becomes the last). import numpy as np
nparr = np.arange(12,38)
print(nparr)
nparr = nparr[::-1]
print(nparr) Write a NumPy program to convert a list and tuple into arrays. import numpy as np
list = [1,2,3]
tuple = tuple(("apple", "banana", "cherry"))
arrLi = np.array(list)
arrTu = np.array(tuple)
print("List to array: ", arrLi)
print("Tuple to array: ", arrTu) Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees and vice versa. Values are stored in a NumPy array. import numpy as np
f = [0, 12, 45.21, 34, 99.91]
c = [-17.78, -11.11, 7.34, 1.11, 37.73, 0. ]
arrF = np.array(f)
arrC = np.array(c)
print("Farenheit values: ", arrF)
print("Farenheit to Celsius: ",np.round((5*arrF/9 - 5*32/9),2))
print("Celsius values: ", arrC)
print("Celsius to Farenheit: ",np.round((9*arrC/5 + 32),2)) Write a NumPy program to find the real and imaginary parts of an array of complex numbers. import numpy as np
arr = np.array([1.00000000+0.j, 0.70710678+0.70710678j])
print("Real part of the array:")
print(arr.real)
print("Imaginary part of the array:")
print(arr.imag) Write a NumPy program to test whether each element of a 1-D array is also present in a second array. import numpy as np
arr1 = np.array([0,10,20,40,60])
arr2 = np.array([0,40])
print(np.in1d(arr1, arr2)) Write a NumPy program to find common values between two arrays. import numpy as np
arr1 = np.array([0,10,20,40,60])
arr2 = np.array([0,40])
print(np.intersect1d(arr1, arr2)) Write a NumPy program to get the unique elements of an array. import numpy as np
arr1 = np.array([10,10,40,40,60])
#arr2 = np.array([0,40])
print(np.unique(arr1)) Write a NumPy program to find the set difference of two arrays. The set difference will return the sorted, unique values in array1 that are not in array2. import numpy as np
arr1 = np.array([10,10,40,40,60])
arr2 = np.array([0,40])
print(np.setdiff1d(arr1,arr2)) Write a NumPy program to find the set exclusive-or of two arrays. Set exclusive-or will return the sorted, unique values in only one (not both) of the input arrays. import numpy as np
arr1 = np.array([ 0,10,20,40,60,80])
arr2 = np.array([10, 30, 40, 50, 70])
print(np.setxor1d(arr1,arr2)) Write a NumPy program to find the union of two arrays. Union will return the unique, sorted array of values in either of the two input arrays. import numpy as np
arr1 = np.array([ 0,10,20,40,60,80])
arr2 = np.array([10, 30, 40, 50, 99])
print(np.union1d(arr1,arr2)) Write a NumPy program comparing two given arrays. import numpy as np
arr1 = np.array([1,2])
arr2 = np.array([4,5])
print(np.greater(arr1,arr2))
print(np.greater_equal(arr1,arr2))
print(np.less(arr1,arr2))
print(np.less_equal(arr1,arr2)) Write a NumPy program to sort along the first, and last axis of an array. import numpy as np
arr1 = np.array([[4, 6],[2, 1]])
#arr2 = np.array([4,5])
print(arr1)
print(np.sort(arr1, axis=0))
print(np.sort(arr1, axis=1)) Write a NumPy program to sort pairs of first name and last name return their indices. (first by last name, then by first name). import numpy as np
arr1 = np.array(["Francisco","Mario","Pedro"])
arr2 = np.array(["Zenteno","Gomez","Martinez"])
print(np.lexsort((arr1, arr2))) Write a NumPy program to get the values and indices of the elements that are bigger than 10 in a given array. import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print("Values bigger than 10: ", x[x>10])
print("Indexes are: ", np.where(x > 10)) Write a NumPy program to create a contiguous flattened array. import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print(np.ravel(x)) Write a NumPy program to create a record array from a (flat) list of arrays. import numpy as np
x = np.array([[1,2,3], ['Red', 'Green', 'White'], [12.20,15,20]])
print(np.core.records.fromarrays([x[0], x[1], x[2]],names='a,b,c')) Write a NumPy program to convert a NumPy array into a Python list structure. import numpy as np
x= np.array([[1,2],[3,4],[5,6]])
print("Array to list", x.tolist()) Write a NumPy program to replace the negative values in a NumPy array with 0. import numpy as np
x= np.array([[-11,2],[3,-34],[5,6]])
print("Original array: ", x)
x[x <0] = 0
print("Negative items to zero: ", x) Write a NumPy program to remove all rows in a NumPy array that contain non-numeric values. import numpy as np
x= np.array([[np.nan,2],[3,34],[5,6]])
print("Original array: ", x)
x[x <0] = 0
print("Fixed array: ",x[~np.isnan(x).any(axis=1)]) Write a NumPy program to select indices satisfying multiple conditions in a NumPy array. Write a NumPy program to count the frequency of unique values in NumPy array. Write a NumPy program to sum and compute the product of NumPy array elements. |
Beta Was this translation helpful? Give feedback.
-
1## 1
list=[12.23, 13.32, 100, 36.32]
print(np.array(list)) 2problem2=np.arange(2,11).reshape(3,3)
print(problem2) 3problem3= np.zeros(10)
problem3[6]=11
print(problem3) 4problem4=np.arange(12,38)
reverse=problem4[::-1]
print(reverse) 5
6sampleArray =[0, 12, 45.21, 34, 99.91]
problem6=np.array(sampleArray)
celsius=(problem6 -32)*5/9
farenheit=(celsius*1.8)+32
print("Celsius",celsius)
print("Farenheit",farenheit) 7originalArray =[ 1.00000000+0.j, 0.70710678+0.70710678j]
problem7=np.array(originalArray)
print("real",problem7.real)
print("Imaginary",problem7.imag) 8array1 = np.array([0, 10, 20, 40, 60])
array2 = np.array([0, 40])
problem8= np.isin(array2, array1)
print(problem8) 9array1 = np.array([0, 10, 20, 40, 60])
array2 = np.array([0, 40])
problem9= np.isin(array2, array1)
print(problem9) 10array1=[0, 10, 20, 40, 60]
array2= [10, 30, 40]
problem10= np.intersect1d(array1, array2)
print(problem10) 11originalArray=np.array([[1, 1],[2, 3]])
problem11=np.unique(originalArray)
print(problem11) 12array2= np.array([10, 30, 40, 50, 70, 90])
array1=np.array([0, 10, 20, 40, 60, 80])
problem12=np.setdiff1d(array1,array2)
print(problem12) 13array1 = [0, 10, 20, 40, 60, 80]
array2 = [10, 30, 40, 50, 70]
problem13=np.setxor1d(array1,array2)
print(problem13) 14array1=[0, 10, 20, 40, 60, 80]
array2= [10, 30, 40, 50, 70]
problem14=np.union1d(array1,array2)
print(problem14) 15arraya= [1, 2]
arrayb= [4, 5]
agreater=np.greater(arraya,arrayb)
print(agreater)
aGreaterEqual= np.greater_equal(arraya,arrayb)
print(aGreaterEqual)
aLess = np.less(arraya,arrayb)
print(aLess)
aLessEqual=np.less_equal(arraya,arrayb)
print(aLessEqual) 16171819202122232425 |
Beta Was this translation helpful? Give feedback.
-
import numpy as np
li = [12.23, 13.32, 100, 36.32]
linp = np.array(li)
print("List:", li,"Type:", type(li))
print("List:", linp,"Type:", type(linp)) import numpy as np
li = np.arange(1, 10)
print("List:", li.ndim)
li = li.reshape(3, 3)
print("List:", li.ndim) import numpy as np
li = np.zeros(10)
print("List:", li)
li[5] = 11
print("List:", li) import numpy as np
li = np.arange(1, 20)
print("List:", li)
li = np.flip(li)
print("List:", li) import numpy as np
li = [1, 1, 3]
li = np.array(li)
print("List", li, "Type", type(li))
tup = ((1,2,3), (4, 5, 6))
tup = np.array(tup)
print("Tuple", tup, "Type", type(tup)) |
Beta Was this translation helpful? Give feedback.
-
#TASK1
import numpy as np
originalList = [12.12, 13.13, 111, 35.24]
arr = np.array(originalList)
print(arr)
#TASK2
import numpy as np
arr = np.arange(2, 11).reshape(3,3)
print(arr)
#TASK3
import numpy as np
arr = np.zeros(10)
arr[6] = 11
print(arr)
#TASK5
import numpy as np
list = [1, 2, 3, 4, 5, 6, 7, 8]
print(np.asarray(list))
tuple = ([8, 4, 6], [1, 2, 3])
print(np.asarray(tuple))
#TASK4
import numpy as np
x = np.arange(12, 38)
print(x)
x = x[::-1]
print(x) |
Beta Was this translation helpful? Give feedback.
-
1.- import numpy as np
a = [1,2,3,4,5]
a_numpy = np.array(a)
print("Original list:")
print(a)
print()
print("List coverted into array:")
print(a_numpy) 2.- import numpy as np
b = np.random.randint(2,11, [3,3])
print(b) 3.- import numpy as np
a = np.zeros(10)
print("Original vector:")
print(a)
a[5] = 11
print("Changing the sixth value to 11...")
print(a) 4.- import numpy as np
a = np.array(range(12, 38))
print("Original array:")
print(a)
print("Reverse array:")
print(np.flip(a)) 5.- import numpy as np
a_list = list(range(0, 10))
b_tuple = tuple((range(0,10)))
a_list_array = np.array(a_list)
b_tuple_array = np.array([b_tuple])
print("Original list:\n",a_list)
print("Array of given list:\n", a_list_array)
print()
print("Original tuple:\n",b_tuple)
print("Array of given tuple:\n", b_tuple_array) 6.- import numpy as np
a_centrigrade = np.array([0, 12, 45.21, 34, 99.91])
b_fahrenheit = np.array([-17.78, -11.11, 7.34, 1.11, 37.73, 0 ])
# Celsius to Fah
# c_to_f = (9/5*[i] + 32)
a_fahrenheit = np.multiply(a_centrigrade,1.8)
a_fahrenheit = np.add(a_fahrenheit,32)
print("Temperature in Celsius: \n",a_centrigrade)
print("Temperature in Fahrenheit: \n",a_fahrenheit)
# Fah to Celsius
# f_to_c = 5([i]-32)/9
b_celsius = np.subtract(b_fahrenheit,32)
b_celsius = np.multiply(b_celsius,0.555)
print("Temperature in Fahrenheit: \n",b_fahrenheit)
print("Temperature in Celsius: \n",b_celsius) 7.- import numpy as np
a = np.array([1 + 5j, 10 + 15j])
print("Original array:\n", a)
print()
print("Real part of complex number given: \n",np.real(a))
print()
print("Imaginary part of complex number given:\n", np.imag(a)) 8.- import numpy as np
a = np.array([0, 10, 20 , 30, 40])
b = np.array([0, 10, ])
print("Origianl array A", a)
print("Origianl array B", b)
print("Compare each element of array 'A' is in Array 'B' ")
print(np.in1d(a, b)) 9.- import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.array([6, 7, 8, 9, 10, 11, 12])
print("Array 1:", a)
print("Array 2:", b)
print("Common values between each array:")
print(np.intersect1d(a, b)) 10.- import numpy as np
a = np.array([1, 1, 2, 2, 3, 4, 5])
print("Original array: ", a)
print("Unique values in given array:")
print(np.unique(a))
b = np.array([(1, 1, 2), (2, 3, 3)])
print("Original array: \n", b)
print("Unique values in given array:")
print(np.unique(b)) 11.- import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
print("Array 1: ", a)
print("Array 2: ", b)
print("The diferrence values in the arrays are:")
print(np.setdiff1d(a, b)) 12.- import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
print("Array 1: ", a)
print("Array 2: ", b)
print("Unique values in only one array (not both) are:")
print(np.setxor1d(a, b)) 13.- import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
print("Array 1: ", a)
print("Array 2: ", b)
print("The unique sorted array of values that are in either of the two input arrays:")
print(np.union1d(a, b)) 14.- import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
print("Array 1: ", a)
print("Array 2: ", b)
print("Array 1 > Array 2: ")
print(np.greater(a, b))
print()
print("Array 1 >= Array 2: ")
print(np.greater_equal(a, b))
print()
print("Array 1 < Array 2: ")
print(np.less(a, b,))
print()
print("Array 1 <= Array 2: ")
print(np.less_equal(a, b)) 15.- import numpy as np
a = np.array([(19, 9,98), (50, 69, 20)])
print("Origianl array")
print(a)
print("sort along the first axis:")
print(np.sort(a,0))
print("sort along the last axis:")
print(np.sort(a)) 16.- import numpy as np
fisrt_name = np.array(['Shelley', 'Margery', 'Lanell', 'Genesis', 'Betsey'])
last_name = np.array(['Battle', 'Plotner', 'Woolum', 'Stahl', 'Brien'])
# Battle, Brien, Plotner, Stahl, Woolum
# 0 4 1 3 2
print(np.lexsort((fisrt_name, last_name))) 17.- import numpy as np
a = np.array([(0, 10, 20), (30, 40, 50)])
print("Original array")
print(a)
print("Values bigger than 10:", a[a>10])
print("Their indices are:", np.where(a>10)) 18.- import numpy as np
a = np.array([(0, 1, 2, 3, 4, 5),(6, 7, 8, 9, 10, 11)])
print("Original array")
print(a)
print("New flatened array:")
print(np.ndarray.flatten(a)) 19.- import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array(['Red','Green','White','Orange'])
c = np.array([12.20, 15 ,20 ,40])
print("Original arrays:")
print(a)
print(b)
print(c)
d = np.core.records.fromarrays([a, b,c], names='a,b,c')
for i in range(np.prod(a.shape)):
print(d[i]) 20.- import numpy as np
a_np = np.array([(0,1),(1,2),(2,3),(3,4)])
a_py = a_np.tolist()
print("Original NumPy array:")
print(a_np)
print("Coversion of NumPy array into Python list:")
print(a_py) 21.- import numpy as np
a = np.array([-1, -4, -5, 0, 5 ,4 ,1])
print("Original array:")
print(a)
for i in range(np.prod(a.shape)):
if a[i] < 0:
a[i] = 0
# Other way to do
# a[a<0] = 0
print("Replace negative numbers with '0':")
print(a) 22.- import numpy as np
a = np.array([(0,1,2),(3,np.nan,5),(np.nan, 5, 6),(7,8,9)])
print("Original array:")
print(a)
# Removing non numerical values
b = a[~np.isnan(a).any(1)]
print("Removal of non-numerical rows")
print(b) 23.- import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print("Original arrays:")
print(a)
print(b)
print("Elements from the second array corresponding in the first element that are greater than 100 and less than 110: ")
true_conditional = (np.logical_and(a>100,a<110))
print(np.where(true_conditional))
print(b[true_conditional])
# Short answer
print(b[np.where(np.logical_and(a>100,a<110))]) 24.- import numpy as np
a = np.array([10, 10, 20, 10, 20, 20, 20, 30, 30, 50, 40, 40])
print("Original array:")
print(a)
unique_values = np.unique(a)
a_py = a.tolist()
unique_py = unique_values.tolist()
count = 0
total = []
for i in range(len(unique_py)):
index = 0
for j in a_py:
if unique_py[i] == a_py[index]:
count+= 1
index += 1
total.append(count)
count = 0
total_np = np.array([unique_py,total])
print("Total of values in the given array: ")
print(total_np) 25.- import numpy as np
a = np.array([5, 8 ,9])
print("Original array:")
print(a)
print("The sum of the elements is:")
print(np.sum(a))
print("The product of the elements is:")
print(np.product(a)) |
Beta Was this translation helpful? Give feedback.
-
#1. import numpy as np
l = [12.23, 13.32, 100, 36.32]
print("Original List:",l)
a = np.array(l)
print("One-dimensional NumPy array: ",a) #2. import numpy as np
x = np.arange(2, 11).reshape(3,3)
print(x) #3. import numpy as np
x = np.zeros(10)
print(x)
print("update sixth value to 11")
x[6] = 11
print(x) #4. import numpy as np
x = np.arange(1, 10)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x) #5. def convert(list):
return tuple(list)
list = [1, 2, 3, 4]
print(convert(list)) #6. import numpy as np
cvalues = [-17.78, -11.11, 7.34, 1.11, 37.73, 0]
C = np.array(cvalues)
print("Values in Centigrade degrees:")
print(C)
print("Values in Fahrenheit degrees:")
print(np.round((9*C/5 + 32),2)) #7. import numpy as np
complex_num = np.array([-1 + 9j, 2 - 77j])
for i in range(len(complex_num)):
print("{}. complex number is {}".format(i + 1, complex_num[i]))
print ("The real part is: {}".format(complex_num[i].real))
print ("The imaginary part is: {}\n".format(complex_num[i].imag)) #11. import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10,30,40]
print("Array2: ",array2)
print("Unique values in array1 that are not in array2:")
print(np.setdiff1d(array1, array2)) #8. import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [0, 40]
print("Array2: ",array2)
print("Compare each element of array1 and array2")
print(np.in1d(array1, array2)) #10. import numpy as np
x = np.array([10, 10, 20, 20, 30, 30])
print("Original array:")
print(x)
print("Unique elements of the above array:")
print(np.unique(x)) #9. import numpy as np
array1 = np.array([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2)) #12. import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
print("Array1: ",array1)
array2 = [10, 30, 40, 50, 70]
print("Array2: ",array2)
print("Unique values that are in only one arrays:")
print(np.setxor1d(array1, array2)) #13. import numpy as np
array1 = np.array([0,1,2,3,4,5,6])
print("Array1: ",array1)
array2 = [1,2,4,6,9,7]
print("Array2: ",array2)
print("Unique in array:")
print(np.union1d(array1, array2)) #14. import numpy as np
a = np.array([1,2])
b = np.array([4,5])
print("Array a: ", a)
print("Array b: ", b)
print("a > b")
print(np.greater(a, b))
print("a >= b")
print(np.greater_equal(a, b))
print("a < b")
print(np.less(a, b))
print("a <= b")
print(np.less_equal(a, b)) #15. import numpy as np
a = np.array([[2,5],[4,4]])
print("Original array:")
print(a)
print("Sort the array along the first axis:")
print(np.sort(a, axis=0))
print("Sort the array along the last axis:")
print(np.sort(a)) #16. import numpy as np
first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
x = np.lexsort((first_names, last_names))
print(x) #17. import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print("Original array: ")
print(x)
print("Values bigger than 10 =", x[x>10])
print("Their indices are ", np.nonzero(x > 10)) #18. import numpy as np
# Creating 3D array
arr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])
print("Original array:\n", arr)
flattened_array = np.ravel(arr)
print("New flattened array:\n", flattened_array) #19. import numpy as np
arr1 = np.array([[5, 10, 15], [20, 25, 30]])
arr2 = np.array([[9, 18, 24], [87.5, 65, 23.8]])
arr3 = np.array([['12', 'bbb', 'john'], ['5.6', '29', 'k']])
# Display the arrays
print("Array1...\n",arr1)
print("Array2...\n",arr2)
print("Array3...\n",arr3)
print("\nArray1 type...\n", arr1.dtype)
print("\nArray2 type...\n", arr2.dtype)
print("\nArray3 type...\n", arr3.dtype)
# Get the dimensions of the Arrays
print("\nArray1 Dimensions...\n", arr1.ndim)
print("\nArray2 Dimensions...\n", arr2.ndim)
print("\nArray3 Dimensions...\n", arr3.ndim)
# To create a record array from a (flat) list of array,
print("\nRecord Array...\n",np.core.records.fromarrays([arr1,arr2,arr3])) #20. import numpy as np
arr = np.array([[0,1],[2,3],[4,5]])
print(f'NumPy Array:\n{arr}')
list1 = arr.tolist()
print(f'List: {list1}') #21. import numpy as np
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
print("initial array", ini_array1)
ini_array1[ini_array1<0] = 0
print("New resulting array: ", ini_array1) #22. import numpy as np
x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]])
print("Original array:")
print(x)
print("Remove all non-numeric elements of the said array")
print(x[~np.isnan(x).any(axis=1)]) #23. import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print("Original arrays")
print(a)
print(b)
print("Elements from the second array corresponding to elements in the first array that are greater than 100 and less than 110:")
print(b[(100 < a) & (a < 110)]) #24. import numpy as np
a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] )
print("Original array:")
print(a)
unique_elements, counts_elements = np.unique(a, return_counts=True)
print("Frequency of unique values of the said array:")
print(np.asarray((unique_elements, counts_elements))) #25. import numpy as np
x = np.array([10, 20, 30], float)
print("Original array:")
print(x)
print("Sum of the array elements:")
print(x.sum())
print("Product of the array elements:")
print(x.prod()) |
Beta Was this translation helpful? Give feedback.
-
#TASK6
import numpy as np
fvalues = [0, 12, 45.21, 34, 99.91, 32]
F = np.array(fvalues)
print(F)
print(np.round((5*F/9 - 5*32/9),2))
#TASK7
import numpy as np
x = np.sqrt([1+0j])
y = np.sqrt([0+1j])
print(x.real)
print(y.imag)
#TASK8
import numpy as np
Array1= np.array([ 0 ,10 ,20 ,40, 60])
Array2= np.array([0, 40])
print(np.in1d(Array1, Array2))
#TASK9
import numpy as np
Array1= np.array([ 0 ,30 ,20 ,40, 60])
Array2= np.array([0, 40,60])
print(np.intersect1d(Array1, Array2))
#TASK10
import numpy as np
x = np.array([60, 10, 20, 20, 40, 30])
print(np.unique(x))
x = np.array([[1, 4], [3, 3]])
print(np.unique(x))
|
Beta Was this translation helpful? Give feedback.
-
#Task25
import numpy as np
arr=np.array([10,20,30])
print(arr.sum())
print(arr.prod())
#Task24
import numpy as np
a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] )
print(a)
unique_ele, counts_ele = np.unique(a, return_counts=True)
print(np.asarray((unique_ele, counts_ele)))
#TASK23
import numpy as np
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
print(b[(100 < a) & (a < 110)])
#TASK22
import numpy as np
x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]])
print(x[~np.isnan(x).any(axis=1)])
#TASK21
import numpy as np
x = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
x[x < 0] = 0
print(x)
`` |
Beta Was this translation helpful? Give feedback.
-
#TASK11
import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
array2 = [10, 30, 40, 50, 70]
print(np.setdiff1d(array1, array2))
#TASK12
import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
array2 = [10, 30, 40, 50, 70]
print(np.setxor1d(array1, array2))
#TASK13
import numpy as np
array1 = np.array([0, 10, 20, 40, 60, 80])
array2 = [10, 30, 40, 50, 70]
print(np.union1d(array1, array2))
#TASK14
import numpy as np
x = np.array([1, 2])
y = np.array([4, 5])
print(np.greater(x, y))
print(np.greater_equal(x, y))
print(np.less(x, y))
print(np.less_equal(x, y))
#TASK15
import numpy as np
x = np.array([[4, 6],[2, 1]])
print(np.sort(x, axis=0))
print(np.sort(x, axis=1))
#TASK16
import numpy as np
Fnames = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
Lnames = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
print(np.lexsort((Fnames, Lnames))) |
Beta Was this translation helpful? Give feedback.
-
Task 1import numpy as np
def main():
li = [12.23, 13.32, 100, 36.32]
print("List:\n", li)
a = np.array(li)
print("Array:\n", a)
if __name__ == '__main__':
main() Task 2import numpy as np
def main():
arra = np.arange(2, 11).reshape(3, 3)
print(arra)
if __name__ == '__main__':
main() Task 3import numpy as np
def main():
x = np.zeros(10)
print(x)
x[6] = 11
print("6th Value to 11:\n", x)
if __name__ == '__main__':
main() Task 4import numpy as np
def main():
arr = np.arange(12, 38)
print("OG Array:\n", arr)
arr = arr[::-1]
print("Reversed Array:\n", arr)
if __name__ == '__main__':
main() Task 5import numpy as np
def main():
listo = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array:\n", np.asarray(listo))
tople = ([8, 4, 6], [1, 2, 3])
print("Tuple to array:\n", np.asarray(tople))
if __name__ == '__main__': main() Task 6import numpy as np
def main():
fahvalues = [0, 12, 45.21, 34, 99.91, 32]
F = np.array(fahvalues)
print("Values in Fahrenheit:\n", F)
print("Values in Celsius:\n", np.round((5 * F / 9 - 5 * 32 / 9), 2))
if __name__ == '__main__': main() Task 7import numpy as np
def main():
a = np.sqrt([1 + 0j])
b = np.sqrt([0 + 1j])
print("Array # 1: ", a)
print("Array # 2: ", b)
print("Real part of the arrays: ")
print(a.real)
print(b.real)
print("Imaginary part of the arrays: ")
print(a.imag)
print(b.imag)
if __name__ == '__main__': main() Task 8import numpy as np
def main():
arr1 = np.array([0, 10, 20, 40, 60])
print("Array1: ", arr1)
arr2 = [0, 40]
print("Array2: ", arr2)
print("Are the elements there?:\n", np.in1d(arr1, arr2))
if __name__ == "__main__": main() Task 9import numpy as np
def main():
arr1 = np.array([0, 10, 20, 40, 60])
arr2 = [10, 30, 40]
print("Array1: ", arr1)
print("Array2: ", arr2)
print("Same values on both:\n", np.intersect1d(arr1, arr2))
if __name__ == '__main__': main() Task 10import numpy as np
def main():
a = np.array([10, 10, 20, 20, 30, 30])
print("Array:\n", a)
print("Unique elements:\n", np.unique(a))
a = np.array([[1, 1], [2, 3]])
print("Array:\n", a)
print("Unique elements:\n", np.unique(a))
if __name__ == '__main__': main() Task 11import numpy as np
def main():
arr1 = np.array([0, 10, 20, 40, 60, 80])
arr2 = [10, 30, 40, 50, 70]
print("Array1:", arr1)
print("Array2:", arr2)
print("Unique elements in Array1:\n", np.setdiff1d(arr1, arr2))
if __name__ == '__main__': main() Task 12import numpy as np
def main():
arr1 = np.array([0, 10, 20, 40, 60, 80])
arr2 = [10, 30, 40, 50, 70]
print("Array 1:", arr1)
print("Array 2:", arr2)
print("Unique values only on one of the arrays:\n", np.setxor1d(arr1, arr2))
if __name__ == "__main__": main() Task 13import numpy as np
def main():
arr1 = np.array([0, 10, 20, 40, 60 ,80])
arr2 = [10, 30, 40, 50, 70]
print("Array1: ", arr1)
print("Array2: ", arr2)
print("Union of the arrays:\n", np.union1d(arr1, arr2))
if __name__ == '__main__': main() Task 14import numpy as np
def main():
a = np.array([1, 2])
b = np.array([4, 5])
print("Array a: ", a)
print("Array b: ", b)
print("a more than b?: ", np.greater(a, b))
print("a more or same as b?: ", np.greater_equal(a, b))
print("a less than b?: ", np.less(a, b))
print("a less or equal to b?: ", np.less_equal(a, b))
if __name__ == '__main__': main() Task 15import numpy as np
def main():
arr = np.array([[4, 6], [2, 1]])
print("OG Array:\n", arr)
narr = np.sort(arr, axis = 0)
print("Sort along the first axis:\n", narr)
nnarr = np.sort(narr, axis = 1)
print("Sort along the last axis:\n", nnarr)
if __name__ == "__main__": main() Task 16import numpy as np
def main():
first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis')
last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl')
news = np.lexsort((first_names, last_names))
print(news)
if __name__ == "__main__": main() Task 17import numpy as np
def main():
arr = np.array([[0, 10, 20], [20, 30, 40]])
print("OG Array:\n", arr)
print("Values more than 10: ", arr[arr > 10])
print("Their indices are: ", np.nonzero(arr > 10))
if __name__ == '__main__': main() Task 18import numpy as np
def main():
arr = np.array([[10, 20, 30], [20, 40, 50]])
print("OG Array:\n", arr)
narr = np.ravel(arr)
print("New flat array:\n", narr)
if __name__ == '__main__': main() Task 19import numpy as np
def main():
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array(['Red', 'Green', 'White', 'Orange'])
arr3 = np.array([12.20, 15, 20, 40])
output = np.core.records.fromarrays([arr1, arr2, arr3], names = 'a, b, c')
print(output[0])
print(output[1])
print(output[2])
if __name__ == '__main__': main() Task 20import numpy as np
def main():
a = np.arange(6).reshape(3, 2)
print("Orginals:\n", a)
print("Array to list:\n", a.tolist())
if __name__ == '__main__': main() Task 21import numpy as np
def main():
arr = np.array([-1, -4, 0, 2, 3, 4, 5, -6])
print("OG Array:\n", arr)
arr[arr < 0] = 0
print("Replace negative values with 0:\n", arr)
if __name__ == '__main__': main() Task 22import numpy as np
def main():
arr = np.array([[1, 2, 3], [4, 5, np.nan], [7, 8, 9], [True, False, True]])
print("OG Array:\n", arr)
print("Remove non-numeric values:\n", arr[~np.isnan(arr).any(axis = 1)])
if __name__ == '__main__': main() Task 23import numpy as np
def main():
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a', 'e', 'i', 'o', 'u'])
print("OG Arrays:")
print(a)
print(b)
print("After conditions:\n", b[(100 < a) & (a < 110)])
if __name__ == '__main__': main() Task 24import numpy as np
def main():
a = np.array([10, 10, 20, 10, 20, 20, 20, 30, 30, 50, 40, 40])
print("First Array:\n", a)
unique_ele, counts = np.unique(a, return_counts = True)
print("Frequnce of unique values:\n", np.asarray((unique_ele, counts)))
if __name__ == '__main__': main() Task 25import numpy as np
def main():
z = np.array([10, 20, 30], float)
print("First Array:\n", z)
print("Sum of the array elements:\n", z.sum())
print("Product of the elements:\n", z.prod())
if __name__ == '__main__': main() |
Beta Was this translation helpful? Give feedback.
-
#TASK17
import numpy as np
array = np.array([[0, 10, 20], [20, 30, 40]])
print(array[array>10])
print(np.nonzero(array > 10))
#TASK18
import numpy as np
array = np.array([[10, 20, 30], [20, 40, 50]])
print(np.ravel(array))
#TASK19
import numpy as np
array1=np.array([1,2,3,4])
array2=np.array(['Red','Green','White','Orange'])
array3=np.array([12.20,15,20,40])
newarray = np.core.records.fromarrays([array1, array2, array3])
print(newarray)
#TASK20
import numpy as np
array1=np.array([[0,1],[2,3],[4, 5]])
print(array1.tolist()) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Write a NumPy program to convert a list of numeric values into a one-dimensional NumPy array.
Expected Output:
Original List: [12.23, 13.32, 100, 36.32]
One-dimensional NumPy array: [ 12.23 13.32 100. 36.32]
Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.
Write a NumPy program to create a null vector of size 10 and update the sixth value to 11.
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Update sixth value to 11
[ 0. 0. 0. 0. 0. 0. 11. 0. 0. 0.]
Write a NumPy program to reverse an array (the first element becomes the last).
Original array:
[12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37]
Reverse array:
[37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12]
Write a NumPy program to convert a list and tuple into arrays.
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]
Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees and vice versa. Values are stored in a NumPy array.
Sample Array [0, 12, 45.21, 34, 99.91]
[-17.78, -11.11, 7.34, 1.11, 37.73, 0. ]
Expected Output:
Values in Fahrenheit degrees:
[ 0. 12. 45.21 34. 99.91 32. ]
Values in Centigrade degrees:
[-17.78 -11.11 7.34 1.11 37.73 0. ]
Values in Centigrade degrees:
[-17.78 -11.11 7.34 1.11 37.73 0. ]
Values in Fahrenheit degrees:
[-0. 12. 45.21 34. 99.91 32. ]
Write a NumPy program to find the real and imaginary parts of an array of complex numbers.
Expected Output:
Original array [ 1.00000000+0.j 0.70710678+0.70710678j]
Real part of the array:
[ 1. 0.70710678]
Imaginary part of the array:
[ 0. 0.70710678]
Write a NumPy program to test whether each element of a 1-D array is also present in a second array.
Expected Output:
Array1: [ 0 10 20 40 60]
Array2: [0, 40]
Compare each element of array1 and array2
[ True False False True False]
Write a NumPy program to find common values between two arrays.
Expected Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]
Write a NumPy program to get the unique elements of an array.
Expected Output:
Original array:
[10 10 20 20 30 30]
Unique elements of the above array:
[10 20 30]
Original array:
[[1 1]
[2 3]]
Unique elements of the above array:
[1 2 3]
Write a NumPy program to find the set difference of two arrays. The set difference will return the sorted, unique values in array1 that are not in array2.
Expected Output:
Array1: [ 0 10 20 40 60 80]
Array2: [10, 30, 40, 50, 70, 90]
Set difference between two arrays:
[ 0 20 60 80]
Write a NumPy program to find the set exclusive-or of two arrays. Set exclusive-or will return the sorted, unique values in only one (not both) of the input arrays.
Array1: [ 0 10 20 40 60 80]
Array2: [10, 30, 40, 50, 70]
Unique values that are in only one (not both) of the input arrays:
[ 0 20 30 50 60 70 80]
Write a NumPy program to find the union of two arrays. Union will return the unique, sorted array of values in either of the two input arrays.
Array1: [ 0 10 20 40 60 80]
Array2: [10, 30, 40, 50, 70]
The unique sorted array of values that are in either of the two input arrays:
[ 0 10 20 30 40 50 60 70 80]
Write a NumPy program comparing two given arrays.
Array a: [1 2]
Array b: [4 5]
a > b
[False False]
a >= b
[False False]
a < b
[ True True]
a <= b
[ True True]
Write a NumPy program to sort along the first, and last axis of an array.
Sample array: [[2,5],[4,4]]
Expected Output:
Original array:
[[4 6]
[2 1]]
Sort along the first axis:
[[2 1]
[4 6]]
Sort along the last axis:
[[1 2]
[4 6]]
Write a NumPy program to sort pairs of first name and last name return their indices. (first by last name, then by first name).
first_names = (Betsey, Shelley, Lanell, Genesis, Margery)
last_names = (Battle, Brien, Plotner, Stahl, Woolum)
Expected Output:
[1 3 2 4 0]
Write a NumPy program to get the values and indices of the elements that are bigger than 10 in a given array.
Original array:
[[ 0 10 20]
[20 30 40]]
Values bigger than 10 = [20 20 30 40]
Their indices are (array([0, 1, 1, 1]), array([2, 0, 1, 2]))
Write a NumPy program to create a contiguous flattened array.
Original array:
[[10 20 30]
[20 40 50]]
New flattened array:
[10 20 30 20 40 50]
Write a NumPy program to create a record array from a (flat) list of arrays.
Sample arrays: [1,2,3,4], ['Red', 'Green', 'White', 'Orange'], [12.20,15,20,40]
Expected Output:
(1, 'Red', 12.2)
(2, 'Green', 15.0)
(3, 'White', 20.0)
Write a NumPy program to convert a NumPy array into a Python list structure.
Expected Output:
Original array elements:
[[0 1]
[2 3]
[4 5]]
Array to list:
[[0, 1], [2, 3], [4, 5]]
Write a NumPy program to replace the negative values in a NumPy array with 0.
Expected Output:
Original array:
[-1 -4 0 2 3 4 5 -6]
Replace the negative values of the said array with 0:
[0 0 0 2 3 4 5 0]
Write a NumPy program to remove all rows in a NumPy array that contain non-numeric values.
Expected Output:
Original array:
[[ 1. 2. 3.]
[ 4. 5. nan]
[ 7. 8. 9.]
[ 1. 0. 1.]]
Remove all non-numeric elements of the said array
[[ 1. 2. 3.]
[ 7. 8. 9.]
[ 1. 0. 1.]]
Write a NumPy program to select indices satisfying multiple conditions in a NumPy array.
Sample array :
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
Note: Select the elements from the second array corresponding to elements in the first array that are greater than 100 and less than 110
Expected Output:
Original arrays
[ 97 101 105 111 117]
['a' 'e' 'i' 'o' 'u']
Elements from the second array corresponding to elements in the first
array that are greater than 100 and less than 110:
['e' 'i']
Write a NumPy program to count the frequency of unique values in NumPy array.
Expected Output:
Original array:
[10 10 20 10 20 20 20 30 30 50 40 40]
Frequency of unique values of the said array:
[[10 20 30 40 50]
[ 3 4 2 2 1]]
Write a NumPy program to sum and compute the product of NumPy array elements.
Expected Output:
Original array:
[ 10. 20. 30.]
Sum of the array elements:
60.0
Product of the array elements:
6000.0
Beta Was this translation helpful? Give feedback.
All reactions