Thursday, September 19, 2019

Numpy Basic-1

NumpyExercise

Basics of Numpy. How to create a numpy array

Data manipulation with Numpy

In [2]:
import numpy as np
In [2]:
a=np.array([1,2,3])
a
Out[2]:
array([1, 2, 3])
In [3]:
a[0]
Out[3]:
1
In [4]:
a[2]
Out[4]:
3

Let's compare Numpy array vs Python list

In [3]:
import time
import sys

Size comp

In [7]:
b=range(1000)
print(sys.getsizeof(b)*len(b))
48000
In [9]:
c=np.arange(1000)
print(c.size*c.itemsize)
4000

Speed comp

In [4]:
size=100000
L1=range(size)
L2=range(size)
A1=np.arange(size)
A2=np.arange(size)
In [5]:
start=time.time()
result=[(x+y) for x,y in zip(L1,L2)]
print("python list took:",(time.time()-start)*1000)
python list took: 24.99556541442871
In [6]:
start=time.time()
result=A1+A2#Convinient
print("Numpy array took:",(time.time()-start)*1000)
Numpy array took: 8.643150329589844
In [16]:
a=np.array([[1,2],[3,4],[5,6]])
a
Out[16]:
array([[1, 2],
       [3, 4],
       [5, 6]])
In [17]:
a.ndim
Out[17]:
2
In [18]:
a.itemsize
Out[18]:
4
In [19]:
a.shape
Out[19]:
(3, 2)
In [20]:
a=np.array([[1,2],[3,4],[5,6]],dtype=np.float64)
a
Out[20]:
array([[1., 2.],
       [3., 4.],
       [5., 6.]])
In [21]:
a.itemsize
Out[21]:
8
In [22]:
a.shape
Out[22]:
(3, 2)
In [23]:
a=np.array([[1,2],[3,4],[5,6]],dtype=np.complex)
a
Out[23]:
array([[1.+0.j, 2.+0.j],
       [3.+0.j, 4.+0.j],
       [5.+0.j, 6.+0.j]])
In [24]:
np.zeros((3,4))
Out[24]:
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
In [25]:
np.ones((3,4))
Out[25]:
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
In [26]:
l=range(5)
l
Out[26]:
range(0, 5)
In [27]:
np.arange(5)
Out[27]:
array([0, 1, 2, 3, 4])
In [28]:
print('Concat Ex:')
print(np.char.add(['hello','hi'],['abc','xy']))
Concat Ex:
['helloabc' 'hixy']
In [29]:
print(np.char.multiply('hello',3))
hellohellohello
In [30]:
print(np.char.center('hello',29,fillchar='*'))
************hello************
In [31]:
print(np.char.capitalize('hello'))
Hello
In [32]:
print(np.char.title('hello, how are you?'))
Hello, How Are You?
In [33]:
print(np.char.lower('hello, how are you?'))
print(np.char.upper('hello, how are you?'))
hello, how are you?
HELLO, HOW ARE YOU?
In [34]:
print(np.char.split('hello, how are you?'))
['hello,', 'how', 'are', 'you?']
In [36]:
print(np.char.splitlines('hello\n how are you?'))
['hello', ' how are you?']
In [37]:
print(np.char.strip(['nina','Shakti','Sampada'],'a'))
['nin' 'Shakti' 'Sampad']
In [38]:
print(np.char.join([':','-'],['20190101','20190201']))
['2:0:1:9:0:1:0:1' '2-0-1-9-0-2-0-1']
In [39]:
print(np.char.replace('Hi How are you?','Hi','Hi,'))
Hi, How are you?
In [ ]:
 

No comments:

Post a Comment