XIAINumpy (1)
XIAINumpy (1)
Creation of 1D array
One dimension array can be created using array method with list object
with one dimensional elements.
e.g.
import numpy as np # np is an alias for NumPy
a = np.array([5,2,3,4]) # Create a 1D Array
print(a) # Output - [5 2 3 4]
print(a[0], a[1], a[2]) # Output - 5 2 3
a[0] = 15 # Change an element of the array
print(a) # Output - [15 2 3 4]
1 D Array
Creation of 1D array using functions:
import numpy as np
p = np.empty(5) # Create an array of 5 elements with random values
print(p)
Numpy Array does not support Python list support adding and
adding and removing of removing of elements
elements
Can’t contain elements of different can contain elements of different
types types
#example:1
import numpy as np
x = np.arange(5) # for float value specify dtype = float as argument
print(x) # print [0 1 2 3 4]
#example:2
import numpy as np
x = np.arange(10,20,2)
print (x) #print [10 12 14 16 18]
Create 1D from array
Copy function is used to create the copy of the existing array.
e.g. program
import numpy as np
x = np.array([1, 2, 3])
y=x
z = np.copy(x)
x[0] = 10
print(x)
print(y)
print(z)
Note :- In the above code both x and y will point to the same array but z will
be the separate array so when we modify x, y changes, but not z.
Output:
[10 2 3]
[10 2 3]
[1 2 3]
1 D ARRAY JOINING
e.g.program
import numpy as np
a = np.array([1, 2, 3])
b = np.array([5, 6])
c=np.concatenate([a,b,a])
print(c) #print [1 2 3 5 6 1 2 3]
Basic arithmetic operation on 1D Array
We can perform all the basic arithmetic operation on array as follows:
import numpy as np
x = np.array([1, 2, 3,4])
y = np.array([1, 2, 3,4])
z=x+y
print(z) #print [2 4 6 8]
z=x-y
print(z) #print [0 0 0 0]
z=x*y
print(z) #print [ 1 4 9 16]
z=x/y
print(z) #print [1. 1. 1. 1.]
z=x+1
print(z) #print [2 3 4 5]
Use of Aggregate function on 1D Array
import numpy as np
x = np.array([1, 2, 3,4])
print(x.sum()) #print 10
print(x.min()) #print 1
print(x.max()) #print 4
import numpy as np
a = np.array([[3, 2, 1],[4, 2, 3]]) # Create a 2D Array
print(a[0][1]) # Prints 2
a[0][1] = 15 # Change an element of the array
print(a) # Prints [[3 15 1]
[4 2 3]]
Creation of 2D array Using functions:
import numpy as np
p = np.empty([2,2]) # Create an array of 4 elements with random values
print(p)