본문 바로가기

Programming/Python

[Python] Numpy 100 exercises # 51 ~ 100

Content

# 51 ~ 100

51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)

Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                  ('y', float, 1)]),
                   ('color',    [ ('r', float, 1),
                                  ('g', float, 1),
                                  ('b', float, 1)])])
print(Z)

 

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)

Z = np.random.random((10,2))
X, Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt((X-X.T**2 + (Y-Y.T)**2)
print(D)

# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson(#issue 1)
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)

 

 

 

 

 

 

 

 

References

1. https://github.com/rougier/numpy-100