Python - NumPy Arrays

Example 1: Using zeros method
x = np.zeros(shape=(2,4))
print(x)
Output
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
Example 2 : Using full method
y = np.full(shape=(2,3), fill_value=10.5)
print(y)
Output
[[ 10.5  10.5  10.5]
 [ 10.5  10.5  10.5]]
Example 3 : Using arange
x = np.arange(3, 15, 2.5) # 2.5 is step
print(x)
Output
[  3.    5.5   8.   10.5  13. ]
Example 4 : Using linspace
y = np.linspace(3, 15, 5) # 5 is size of array 'y'
print(y)
Output
[  3.   6.   9.  12.  15.]
Example 5 : Using random
np.random.seed(100) # setting seed
x = np.random.rand(2) # 2 random numbers between 0 and 1

print(x)
Output
[ 0.54340494  0.27836939]
Example 6
np.random.seed(100) # setting seed
y = np.random.randint(10, 50, 3) # 3 random integers between 10 and 50

print(y)
Output
[18 34 13]
Example 7
np.random.seed(100)
x = np.random.randn(3) # Standard normal distribution

print(x)
Output
[-1.74976547  0.3426804   1.1530358 ]
Example 8
np.random.seed(100)
x = 10 + 2*np.random.randn(3) # normal distribution with mean 10 and sd 2

print(x)
Output
[  5.62558632  10.85670101  12.88258951]
Example 9
from io import StringIO
import numpy as np

x = StringIO('''88.25 93.45 72.60 90.90
72.3 78.85 92.15 65.75
90.5 92.45 89.25 94.50
''')

d = np.loadtxt(x,delimiter=' ')

print(d)

print(d.ndim, d.shape)
Output
[[ 88.25  93.45  72.6   90.9 ]
 [ 72.3   78.85  92.15  65.75]
 [ 90.5   92.45  89.25  94.5 ]]
2 (3, 4)

No comments:

Post a Comment