008.tricks and Tips
008.tricks and Tips
008.tricks and Tips
To change the dimensions of an array, you can omit one of the sizes
which will then be deduced automatically:
>>> a = np.arange(30)
>>> a.shape = 2,-1,3 # -1 means "whatever is needed"
>>> a.shape
(2, 5, 3)
>>> a
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]],
[[15, 16, 17],
[18, 19, 20],
[21, 22, 23],
[24, 25, 26],
[27, 28, 29]]])
[demo]
import numpy as np
a = np.arange(30)
a.shape = 2,-1,3 # -1 means "whatever is needed"
print(a.shape)
print(a)
[/demo]
::
x = np.arange(0,10,2) # x=([0,2,4,6,8])
y = np.arange(5) # y=([0,1,2,3,4])
m = np.vstack([x,y]) # m=([[0,2,4,6,8],
# [0,1,2,3,4]])
xy = np.hstack([x,y]) # xy =([0,2,4,6,8,0,1,2,3,4])
[demo]
import numpy as np
x = np.arange(0,10,2) # x=([0,2,4,6,8])
y = np.arange(5) # y=([0,1,2,3,4])
m = np.vstack([x,y]) # m=([[0,2,4,6,8],
xy = np.hstack([x,y]) # xy =([0,2,4,6,8,0,1,2,3,4])
print(x)
print(y)
print(m)
print(xy)
[/demo]
The logic behind those functions in more than two dimensions can be
strange.
.. seealso::
:doc:`numpy-for-matlab-users`
8.3 Histograms
----------
.. plot::
[demo]
import numpy as np
import matplotlib.pyplot as plt
# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
# Plot a normalized histogram with 50 bins
plt.hist(v, bins=50, normed=1) # matplotlib version (plot)
plt.show()
# Compute the histogram with numpy and then plot it
(n, bins) = np.histogram(v, bins=50, normed=True) # NumPy version (no plot)
plt.plot(.5*(bins[1:]+bins[:-1]), n)
plt.show()
[/demo]