# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # CH 4. Arrays and Vectorized Computation

# ## 1. Import Package

import numpy as np
import matplotlib.pyplot as plt
from random import normalvariate
import random

my_list=list(range(1000000))
my_arr=np.arange(1000000)

# %time 
for _ in range(10) : my_list*2

# %time 
for _ in range(10) : my_arr*2

# ## 2. Creating ndarray

arr=np.random.randn(2,3)
arr

# +
print(arr*10)
print(arr+arr)

print("shape of data :",arr.shape)
print("data type of data :",arr.dtype)
print("type of data :" ,type(arr))
# -

data1=[6,7.5,8,0,1]
arr1=np.array(data1)
arr1

data2=[[1,2,3,4],[5,6,7,8]]
arr2=np.array(data2)
arr2

print("arr1 :",arr1.ndim)
print("arr2 :",arr2.ndim)
print("arr1 :",arr1.dtype)
print("arr2 :",arr2.dtype)

# ## 3. dtypes for ndarray

# +
arr1=np.array([1,2,3],dtype=np.float64)
arr2=np.array([1,2,3],dtype=np.int32)

print(arr1.dtype)
print(arr2.dtype)
# -

arr=np.array([1,2,3,4,5])
arr.dtype

float_arr=arr.astype(np.float64)
float_arr.dtype

arr=np.array([3.7,-1.2,-2.6,0.5,12.9,10.1])
arr.astype(np.int32)

numeric_strings=np.array(['1.25','-9.6','42'],dtype=np.string_)
numeric_strings.astype(float)

# ## 4. Arithmetic with numpy arrays

arr=np.array([[1,2,3],[4,5,6]])
arr

print(arr*arr)
print(arr-arr)
print(1/arr)
print(arr**0.5)

arr2=np.array([[0,4,1],[7,2,12]])
arr2

print(arr2>arr)

# ## 5. Basic indexing and slicing

# 1 dimensional
arr=np.arange(10)
arr

print(arr[5])
print(arr[5:8])

arr[5:8]=12
arr

arr_slice=arr[5:8]
arr_slice

arr_slice[1]=12345
arr

arr_slice[:]=64
arr

# 2 dimensional
arr2d=np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2d

print(arr2d[0])
print(arr2d[0][2])
print(arr2d[0,2])

# 3 dimensional
arr3d=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
arr3d

print(arr3d[0])
print(arr3d[0][1])
print(arr3d[0][1][0])

# selection with slicing
arr

print(arr[1:6])

arr2d

print(arr2d[:2])
print(arr2d[:2,1:])
print(arr2d[1,:2])

# ## 6. Boolean Indexing

names=np.array(['Bob','Joe','Will','Bob','Will','Joe','Joe'])
data=np.random.randn(7,4)
print(names)
print(data)

print("[1]", names=='Bob')
print("[2]", data[names=='Bob'])
print("[3]", data[names=='Bob',2:])
print("[4]", data[names=='Bob',3])
print("[5]", names!='Bob')
print("[6]", data[~(names=='Bob')])

cond = names=='Bob'
data[~cond]

mask = (names=='Bob') | (names=='Will')
mask

data[mask]

data[data<0]=0
data

data[names !='Joe']=7
data

# ## 7. Fancy Indexing

arr = np.empty((8,4))
arr

for i in range(8):
    arr[i]=i
arr

print(arr[[4,3,0,6]])
print(arr[[-3,-5,-7]])

arr = np.arange(32).reshape((8,4))
arr

print(arr[[1,5,7,2],[0,3,1,2]])
print(arr[[1,5,7,2]][:,[0,3,1,2]])

arr = np.arange(15).reshape((3,5))
print(arr)
print(arr.T)

arr=np.random.randn(6,3)
print(arr)
print(np.dot(arr.T,arr))

# ## 8. Universal Function : Fast element-wise array function

arr=np.arange(10)
print(arr)
print(np.sqrt(arr))
print(np.exp(arr))

x=np.random.randn(8)
y=np.random.randn(8)
print(x)
print(y)

print(np.maximum(x,y))
print(np.minimum(x,y))

# ## 9. Array-oriented programming with arrays

points = np.arange(-5,5,0.01)

xs,ys=np.meshgrid(points,points)

print(xs)
print(ys)

z = np.sqrt(xs**2+ys**2)
z

# +
plt.imshow(z, cmap=plt.cm.gray);plt.colorbar()
plt.title("Image plot of $\sqrt{x^2+y^2}$ for a gird of values")

plt.show()
# -

# ## 10. Expressing Conditional Logic as array operations

xarr = np.array([1.1,1.2,1.3,1.4,1.5])
yarr = np.array([2.1,2.2,2.3,2.4,2.5])
cond = np.array([True,False,True,True,False])

result=[(x if c else y)
        for x,y,c in zip(xarr,yarr,cond)]
result

result_=np.where(cond,xarr,yarr)
result_

arr=np.random.randn(4,4)
arr

print(arr>0)
print(np.where(arr>0,2,-2))
print(np.where(arr>0,2,arr))

# ## 11. Mathematical and Statistical Methods

# +
arr=np.random.randn(5,4)

print(arr)
print(arr.mean())
print(np.mean(arr))
print(arr.sum())
print(arr.mean(axis=1))
print(arr.sum(axis=1))

# +
arr = np.array([0,1,2,3,4,5,6,7])

print(arr)
print(arr.cumsum())

# +
arr = np.array([[0,1,2],[3,4,5],[6,7,8]])

print(arr)
print(arr.cumprod(0))
print(arr.cumprod(axis=0))
# -

# ## 12. Method for Boolean Arrays

# +
arr = np.random.randn(100)

print(arr)
print((arr>0).sum())

# +
bools = np.array([False,False,True,False])

print(bools.any())
print(bools.all())
# -

# ## 13. Sorting

arr = np.random.randn(6)
arr

arr.sort()
arr

arr=np.random.randn(5,3)
arr

arr.sort(1)
arr

large_arr = np.random.randn(1000)
large_arr.sort()

large_arr[int(0.05*len(large_arr))]

# ## 14. Unique and other Set logics

names=np.array(['Bob','Joe','Will','Bob','Will','Joe','Joe'])
np.unique(names)

ints = np.array([3,3,3,2,2,1,1,4,4])
np.unique(ints)

sorted(set(names))

values = np.array([6,0,0,3,2,5,6])
np.in1d(values,[2,3,6])

# ## 15. File Input and Output with Arrays

arr = np.arange(10)
np.save('some_array',arr)

np.load('some_array.npy')

np.savez('array_archive.npz',a=arr,b=arr)

arch=np.load('array_archive.npz')
arch['b']

np.savez_compressed('arrays_compressed.npz',a=arr,b=arr)

# ## 16. Linear Algebra

# +
x = np.array([[1,2,3],[4,5,6]])
y = np.array([[6.,23.],[-1,7],[8,9]])

print(x)
print(y)
# -

x.dot(y)  # np.dot(x,y)

np.dot(x,np.ones(3)) #x@np.ones(3)

# ## 17. Random

samples=np.random.normal(size=(4,4))
samples

N=1000000
# %timeit samples =[normalvariate(0,1) for _ in range(N)]

# %timeit np.random.normal(size=N)

# ## 18. Example

position = 0
walk = [position]
steps = 1000    

for i in range(steps) : 
    step = 1 if random.randint(0,1) else -1
    position += step
    walk.append(position)

plt.plot(walk[:100])
plt.show()

StarcoderdataJupyterScriptsDedupFiltered