What is the preferred way to handle basic arrays in Python?

Question:

I am in the processing of learning python after using Matlab for years. I’ve run into a snag and I’m not finding much help in my google search.

I would like to know the best way to handle basic arrays. Should I be using numpy, scipy, array, numarray, or something else?

For example, take the following Matlab code.

a = rand(10,1)
b = rand(10,1)


c = b > 0.5
d = a .* b
e = a + b
f = mean(a)
g = sum(b)

What would be the best way to convert this to python?

Asked By: Miebster

||

Answers:

You should definitely go with NumPy if you’ll be doing math with arrays of numbers; there’s even a migration guide for MATLAB users.

NumPy does a lot of the same array-broadcasting that MATLAB does, so it should be pretty natural to use. Your code can be written as:

import numpy as np
a = np.random.rand(10,1)
b = np.random.rand(10,1)
c = b > 0.5
d = a * b # Note that * in NumPy is always elementwise (use .dot for matrix multiplication)
e = a + b
f = a.mean() # Can also use np.mean(a)
g = b.sum() # Can also use np.sum(b)
Answered By: nneonneo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.