Installation using pip for Python 3
pip3 install numpy
import numpy as np
Convert list to NumPy ndarray
l1 = [1,2,3]
l2 = [4,5,6]
arr1 = np.array(l1)
arr2 = np.array(l2)
print(arr1*arr2)
[ 4 10 18]
NumPy ndarray attributes
size
T #transpose
ndim
np.inf #infinite value
print(arr1.ndim)
1
shape
print(arr1.shape)
(3,)
arr2d = np.array([[1,2,3],
[4,5,6]])
print(arr2d.shape)
(2, 3)
NumPy ndarray methods
min()
max()
mean()
std()
sum()
reshape()
arr2d.reshape(3,2)
array([[1, 2],
[3, 4],
[5, 6]])
flatten()
arr2d.flatten()
array([1, 2, 3, 4, 5, 6])
tolist()
arr2d.tolist()
[[1, 2, 3], [4, 5, 6]]
NumPy methods
np.sqrt(value)
np.zeros(shape)
np.ones(shape)
np.full(shape,value)
np.mean(arr)
np.median(arr)
np.log(arr)
df['col1']=np.where((df['col2']>=0) & (df['col2']<=100),True,False) #importance: each condition must be surrounded by parentheses
df['col1']=np.where(df['col1']==np.inf, 0, df['col1']) #equivalent to the following
df.loc[df['col1']==np.inf,'col1']=0