Hide
Don't get spied on – We respect your privacy and provide numerous options to protect it. Join Siafoo Now or Learn More

NumPy Tips and Tricks Atom Feed 0

A collection of various NumPy tips and trick that I always forget

1   Misc

1.1   Index Coordinates

The indices function is perfect for generating index coordinate pairs for N-Dimensional arrays.

# 's
 1# Indices for all elements of a 2x2 array
2i = indices((2, 2)).reshape(2, -1).T # [[0, 0], [0, 1], [1, 0], [1,1]]
3
4# Indices for all elements of a Width X Height Image
5i = indices((width, height)).reshape(2, -1).T
6
7# Coordinates for a unit cube
8i = indices((2, 2, 2)).reshape(3, -1).T # [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0] ... ]
9
10# Coordinates for a Width X Height X Depth 3D dataset
11i = indices((width, height, depth)).reshape(3, -1).T

1.2   Python-like min/max

The python min/max functions return the lowest/highest value between two given values, thus allowing a variable to be clamped. One way to perform a similar operation on a NumPy array is:

# 's
1a = array([1.2, 1.0, 0.0, 0.2, -0.2, 0.5, -0.5])
2
3a[a > 1.0] = 1.0 # max
4# a == array([1.0, 1.0, 0.0, 0.2, -0.2, 0.5, -0.5])
5
6a[a < 0.0] = 0.0 # min
7# a == array([1.0, 1.0, 0.0, 0.2, 0.0, 0.5, 0.0])

2   Image Manipulation

2.1   Array from Image

Get the data from a PIL image, as an array [1] :

a = numpy.asarray(image)

3   Resources

NumPy Documentation The main page for the NumPy documentation

NumPy Example List A list of examples for every NumPy function

4   Conclusion

If you have suggestions for improving this list, feel free to add them in, or drop me a line.

[1]Chris Barker's comment