2022 Developer Survey is open! Take survey.

Hot answers tagged

32 votes
Accepted

Looking for a way to create a particular matrix in python in a less amount of time

The NumPy Reference should be the first place you look when you have a problem like this. The operations you need are nearly always in there somewhere. And functions that you find while browsing the ...
user avatar
  • 49.2k
31 votes
Accepted

Scale Numpy array to certain range

NumPy provides numpy.interp for 1-dimensional linear interpolation. In this case, where you want to map the minimum element of the array to −1 and the maximum to +1,...
user avatar
  • 49.2k
28 votes
Accepted

Crop black border of image using NumPy

Vectorization with NumPy When read with cv2.imread or skimage.io.imread or scipy.misc.imread,...
user avatar
  • 886
25 votes
Accepted

Remove points in a straight line

A look at the second plot in the post shows that something has gone wrong. There are four points in a line here: This shouldn't be possible, since "points that create a straight line when plotted" ...
user avatar
  • 49.2k
22 votes

Crop black border of image using NumPy

As you've discovered, looping over individual pixels in Python is very slow. You need to organize your computation so that it uses a series of NumPy (or SciPy, or Scikit-Image, or OpenCV) operations ...
user avatar
  • 49.2k
21 votes

Finding the closest point to a list of points

All your code could be rewritten as: ...
user avatar
  • 351
19 votes

Efficient numpy cosine distance calculation

Your code does not run: there are missing import statements: import numpy as np import scipy.spatial.distance Your algorithms ...
user avatar
  • 49.2k
18 votes

Generating a 3D Point Cloud

1. Review No docstring. What does this function do? What parameters does it take? What shape must the depth_image parameter be? What does it return? In Python, ...
user avatar
  • 49.2k
18 votes
Accepted

Remove pixel patch in image which is stored as array

On my computer it takes 1.745 seconds to run the code in the post. There's no need for the array of random indexes to be two-dimensional: ...
user avatar
  • 49.2k
18 votes
Accepted

Iterate through two arrays calculating a statistic from indexes of zeros

First, some basics of your implementation: Type-hint your arguments; I had to read and investigate a bunch to deduce that tau is a positive integer ...
user avatar
  • 47.9k
16 votes
Accepted

Sending a C++ array to Python/NumPy and back

1. Review It's not recommended to use using namespace std; — the problem is that this imports all of the identifiers from std, ...
user avatar
  • 49.2k
15 votes
Accepted

Approximate (250 over 100) permutation best fitting certain criteria

1. Analysis In the general case, the problem of finding the sample of words with the "most even" distribution of letters is NP-hard. Here I'm considering a general instance of this problem to be: ...
user avatar
  • 49.2k
15 votes
Accepted

Comparing pixels against RGB value in NumPy

Your original code can be rewritten as: mask = np.all(img == (255, 127, 63), axis=-1) It is a little cleaner, but not more efficient, as it still has to allocate ...
user avatar
  • 6,512
14 votes
Accepted

Possible optimizations for calculating squared euclidean distance

You can decrease Python's overhead by parsing the args tuple and creating the return value manually. Try changing these portions of your code: ...
user avatar
  • 351
14 votes
Accepted

K-Mean with Numpy

1. Code review There's no documentation. What do your functions do and how am I supposed to call them? There are no test cases. What gives you confidence that the algorithm is correct? The algorithm ...
user avatar
  • 49.2k
13 votes
Accepted

Optimizing very simple piece of “Game of Life” code by taking advantage of NumPy's functionality

I'll just be cheeky and post a slightly modified version of my SO answer here. So first things first, you want to get rid of the loops. They are slow to execute. The first loop: ...
user avatar
  • 586
13 votes
Accepted

Balanced Random Assignment in Python

Just create a list of 18 ones and 18 twos, shuffle it, then reshape to 6x6: ...
user avatar
  • 401
13 votes
Accepted

Python program that draws the Mandelbrot set fractal

The key thing to remember when working with numerical code is that the CPython interpreter is pretty slow (it trades speed for flexibility) and so you must avoid running in the interpreter whenever ...
user avatar
  • 49.2k
13 votes

Processing an image to extract green-screen mask

Use conditional indexing: ...
user avatar
  • 12.1k
12 votes
Accepted

Groupby in NumPy

The function scipy.ndimage.find_objects returns exactly the slices that you are looking for: ...
user avatar
  • 49.2k
12 votes
Accepted

Processing an image to extract green-screen mask

There's a simpler way to create the empty image using numpy.zeros_like: empty_img = numpy.zeros_like(img) As Austin Hastings ...
user avatar
12 votes
Accepted

Optimize Performance of Region Checking in List Comprehension

Loops over large arrays are not really a good idea in Python. This is why your original list comprehension is not terribly fast. Your numpy version is loop free, but as far as I know, ...
user avatar
  • 7,184
12 votes
Accepted

How to clean the indexes, and ideally not create an additional array

Here is a review of the solution. ^ is xor in Python. It is not for computation of exponentials. When running code outside a method / class, it is a good practice ...
user avatar
  • 2,281
11 votes
Accepted

Order a list of tuples or a NumPy array in a specific format

This is really a graph problem! Draw a graph with a vertex for every number in your list, and an edge between vertices \$a\$ and \$b\$ if there is a pair \$(a, b)\$ or \$(b, a)\$ in your list: What ...
user avatar
  • 49.2k
11 votes
Accepted

Combining two clock tick vectors with NumPy

Everything apart from the for loop in your code is already vectorized which leaves only the for loop to be optimized. You ...
user avatar
  • 226
11 votes
Accepted

Recursively Save Python Dictionaries to HDF5 Files Using h5py

Here's what I tested. I took out the classmethod stuff to make it easier to read, and simplified names a bit. I'll defer judgement on whether that stuff is needed as part of a larger package or not. ...
user avatar
  • 1,441
11 votes
Accepted

Plot timings for a range of inputs

matplotlib adding stuff to the current figure is because you are not using the OO-interface. It is slightly clunkier, but allows way more freedom In my view, you ...
user avatar
11 votes
Accepted

Table of Tribonacci sequence using NumPy and PANDAS

You’re using the wrong tool for the job. Basically, you do all the computation in Python, use numpy for intermediate storage and ...
user avatar
11 votes
Accepted

Solve the phase state between two haplotype blocks using markov transition probabilities

Before we get to the interesting stuff, we should handle some stylistic niggles. Note that PEP 8 is a de-facto style for Python code. First, imports should be sorted ...
user avatar
  • 9,523
11 votes

Remove points in a straight line

You can use Ramer Douglas Peuker algorithm. RDP takes a curve and eliminates points that are close to straight lines. It is distance based. Starting with the two endpoints, it forms a line and picks ...
user avatar

Only top scored, non community-wiki answers of a minimum length are eligible