Python Numpy tricks

Axis

Repeating an array


In [33]:
# Repeat a Python list
[1, 3]*5


Out[33]:
[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]

In [34]:
# repeat at Numpy array
np.array([1, 3]*5)


Out[34]:
array([1, 3, 1, 3, 1, 3, 1, 3, 1, 3])

In [46]:
tile([1, 3], 5) # also transforms a Python list into Numpy array


Out[46]:
array([1, 3, 1, 3, 1, 3, 1, 3, 1, 3])

In [54]:
repeat([1, 3], 5) # repeat the elements ! also transforms a Python list into Numpy array


Out[54]:
array([1, 1, 1, 1, 1, 3, 3, 3, 3, 3])

In [37]:
# Pay attention that r_ or c_ not repeat but instead perform element multiplication
r_[1, 3]*5


Out[37]:
array([ 5, 15], dtype=int32)

Creating 1D vectors from multiple 1D vectors

Let $a$ and $b$ two vectors of different length, for example: $$ a = \left( 1 , 2 , 3 \right) $$ and $$ b = \left(4, 5\right) $$ We would like new vectors $a_2$ and $b_2$ with the same length and such that: $$ \begin{array}{l} a_2 = \left(1, 2, 3, 1, 2, 3\right)\\ b_2 = \left(4, 4, 4, 5, 5, 5\right) \end{array} $$


In [53]:
# method 1
a = np.array([1,2,3])
b = np.array([4, 5])
a2 = tile(a, len(b))
b2 = repeat(b, len(a))
print(a2)
print(b2)


[1 2 3 1 2 3]
[4 4 4 5 5 5]

In [52]:
# method 2
a = np.array([1,2,3])
b = np.array([4, 5])
aa, bb = meshgrid(a,b)
a2 = reshape(aa, len(a)*len(b))
b2 = reshape(bb, len(a)*len(b))
print(a2)
print(b2)


[1 2 3 1 2 3]
[4 4 4 5 5 5]

css


In [1]:
from IPython.core.display import HTML
def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()


---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-1-ac20ed0cbd9b> in <module>()
      3     styles = open("../styles/custom.css", "r").read()
      4     return HTML(styles)
----> 5 css_styling()

<ipython-input-1-ac20ed0cbd9b> in css_styling()
      1 from IPython.core.display import HTML
      2 def css_styling():
----> 3     styles = open("../styles/custom.css", "r").read()
      4     return HTML(styles)
      5 css_styling()

FileNotFoundError: [Errno 2] No such file or directory: '../styles/custom.css'

In [ ]: