Create an ndarray¶

In [1]:
import numpy as np

np.array(['a', 'b'])
Out[1]:
array(['a', 'b'], dtype='<U1')
In [2]:
np.zeros(3)
Out[2]:
array([0., 0., 0.])
In [3]:
np.full(3, 2.71)
Out[3]:
array([2.71, 2.71, 2.71])
In [4]:
np.arange(0, 10, 2) # 2-spaced values over [0, 10)
Out[4]:
array([0, 2, 4, 6, 8])
In [5]:
A = np.arange(6)
A.shape
Out[5]:
(6,)
In [6]:
A.reshape((-1, 2)) # '-1' requests #rows to be inferred
Out[6]:
array([[0, 1],
       [2, 3],
       [4, 5]])
In [7]:
np.linspace(0, 10)
Out[7]:
array([ 0.        ,  0.20408163,  0.40816327,  0.6122449 ,  0.81632653,
        1.02040816,  1.2244898 ,  1.42857143,  1.63265306,  1.83673469,
        2.04081633,  2.24489796,  2.44897959,  2.65306122,  2.85714286,
        3.06122449,  3.26530612,  3.46938776,  3.67346939,  3.87755102,
        4.08163265,  4.28571429,  4.48979592,  4.69387755,  4.89795918,
        5.10204082,  5.30612245,  5.51020408,  5.71428571,  5.91836735,
        6.12244898,  6.32653061,  6.53061224,  6.73469388,  6.93877551,
        7.14285714,  7.34693878,  7.55102041,  7.75510204,  7.95918367,
        8.16326531,  8.36734694,  8.57142857,  8.7755102 ,  8.97959184,
        9.18367347,  9.3877551 ,  9.59183673,  9.79591837, 10.        ])
In [8]:
a = np.arange(3) # show with a = [0, 1, 2] at pythontutor.com|
copy = a.copy()
copy[0] = 10 # does not change a
view = a
view[1] = 11 # changes a
print(f'a={a}, copy={copy}, view={view}')
a=[ 0 11  2], copy=[10  1  2], view=[ 0 11  2]

Array types (dtype)¶

In [9]:
np.array([1, 2, 3])
Out[9]:
array([1, 2, 3])
In [10]:
A = np.array([1, np.sqrt(2), np.e, np.pi])
A
Out[10]:
array([1.        , 1.41421356, 2.71828183, 3.14159265])
In [11]:
1 < A
Out[11]:
array([False,  True,  True,  True])
In [12]:
np.sum(1 < A)
Out[12]:
3
In [13]:
np.array(['apple', 'banana', 'cherry'])
Out[13]:
array(['apple', 'banana', 'cherry'], dtype='<U6')

A few functions¶

In [14]:
np.amax(A)
Out[14]:
3.141592653589793
In [15]:
np.argmax(A)
Out[15]:
3
In [16]:
x = 1 + np.arange(5)
print(x)
np.std(x, ddof=1) 
[1 2 3 4 5]
Out[16]:
1.5811388300841898
In [17]:
B = np.array([13, 10, 12, 11])
B
Out[17]:
array([13, 10, 12, 11])
In [18]:
np.sort(B)
Out[18]:
array([10, 11, 12, 13])
In [19]:
np.argsort(B)
Out[19]:
array([1, 3, 2, 0])
In [20]:
B[np.argsort(B)]
Out[20]:
array([10, 11, 12, 13])
In [21]:
np.flip(np.sort(B)) # np.flip() reverses an array
Out[21]:
array([13, 12, 11, 10])
In [22]:
price = np.array((10, 15, 12)) # use np.argsort() to sort two parallel arrays
n_shares = np.array((1, 2, 5)) # while keeping them parallel
indicesToSortPrice = np.argsort(price)
indicesToSortPrice
Out[22]:
array([0, 2, 1])
In [23]:
price[indicesToSortPrice]
Out[23]:
array([10, 12, 15])
In [24]:
n_shares[indicesToSortPrice]
Out[24]:
array([1, 5, 2])
In [25]:
np.isin(np.array([1, 2, 3]), np.array([2, 7]))
Out[25]:
array([False,  True, False])

Aside: What's the difference between [], (), and {}?¶

[] enclose a list; and [] are for indexing into a sequence (string, tuple, list) or array, e.g. price[2]

() enclose a tuple; and () enclose the arguments to a function, e.g. np.sort(price)

We have used {} only in a print(f'...') statement to say, "give the value of the enclosed variable," e.g print(f'x={x}')

Operators (which act element-wise)¶

In [26]:
x = 1 + np.arange(5)
x
Out[26]:
array([1, 2, 3, 4, 5])
In [27]:
n = len(x)
np.sqrt(np.sum((x - np.mean(x))**2) / (n - 1)) # no loop; inspect parts
Out[27]:
1.5811388300841898
In [28]:
# We could not do this with a list--thus the Q03 exercises
# to find std(x), where x was a list, required a loop. NumPy was
# written to make this kind of computation easier, faster, and
# less memory-intensive.
y = [1, 2, 3]
# y - 2 # uncomment to see error: can't do this with a list (without a loop)
In [29]:
A
Out[29]:
array([1.        , 1.41421356, 2.71828183, 3.14159265])
In [30]:
1 < A
Out[30]:
array([False,  True,  True,  True])
In [31]:
A < 3
Out[31]:
array([ True,  True,  True, False])
In [32]:
(1 < A) & (A < 3)
Out[32]:
array([False,  True,  True, False])
In [33]:
(1 < A) | (A < 3)
Out[33]:
array([ True,  True,  True,  True])
In [34]:
(1 < A) ^ (A < 3)
Out[34]:
array([ True, False, False,  True])
In [35]:
~(1 < A)
Out[35]:
array([ True, False, False, False])

Indexing¶

In [36]:
A[0]
Out[36]:
1.0
In [37]:
A[3]
Out[37]:
3.141592653589793
In [38]:
A[-1]
Out[38]:
3.141592653589793
In [39]:
A[0:2]
Out[39]:
array([1.        , 1.41421356])
In [40]:
A[:2]
Out[40]:
array([1.        , 1.41421356])
In [41]:
A[0:]
Out[41]:
array([1.        , 1.41421356, 2.71828183, 3.14159265])
In [42]:
x = np.arange(10, 20)
x
Out[42]:
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
In [43]:
a = np.array([0, 9])
a
Out[43]:
array([0, 9])
In [44]:
x[a]
Out[44]:
array([10, 19])
In [45]:
x[np.array([0, -1])]
Out[45]:
array([10, 19])
In [46]:
A
Out[46]:
array([1.        , 1.41421356, 2.71828183, 3.14159265])
In [47]:
indices = np.nonzero(1 < A)
indices
Out[47]:
(array([1, 2, 3]),)
In [48]:
A[indices]
Out[48]:
array([1.41421356, 2.71828183, 3.14159265])
In [49]:
A[1 < A]
Out[49]:
array([1.41421356, 2.71828183, 3.14159265])
In [50]:
x
Out[50]:
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
In [51]:
x % 2
Out[51]:
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
In [52]:
(x % 2) == 0
Out[52]:
array([ True, False,  True, False,  True, False,  True, False,  True,
       False])
In [53]:
x[(x % 2) == 0]
Out[53]:
array([10, 12, 14, 16, 18])
In [54]:
np.all(1 < A)
Out[54]:
False
In [55]:
np.any(1 < A)
Out[55]:
True

Loop through values or indices, as with sequences¶

In [56]:
for value in x:
    print(f'  value={value}')
  value=10
  value=11
  value=12
  value=13
  value=14
  value=15
  value=16
  value=17
  value=18
  value=19
In [57]:
for i in np.arange(len(x)):
    print(f'  i={i}, x[{i}]={x[i]}')
  i=0, x[0]=10
  i=1, x[1]=11
  i=2, x[2]=12
  i=3, x[3]=13
  i=4, x[4]=14
  i=5, x[5]=15
  i=6, x[6]=16
  i=7, x[7]=17
  i=8, x[8]=18
  i=9, x[9]=19

File input/output¶

In [58]:
np.savetxt('A.txt', A)
In [59]:
C = np.loadtxt('A.txt', float)
C
Out[59]:
array([1.        , 1.41421356, 2.71828183, 3.14159265])
In [ ]: