Skip to content

Instantly share code, notes, and snippets.

@fauxneticien
Created June 4, 2022 16:03
Show Gist options
  • Save fauxneticien/2ff31c5ec32e2545e9bf749fc9b15d08 to your computer and use it in GitHub Desktop.
Save fauxneticien/2ff31c5ec32e2545e9bf749fc9b15d08 to your computer and use it in GitHub Desktop.
Python equivalent for R's expand grid
# Adapted from https://stackoverflow.com/questions/12130883/r-expand-grid-function-in-python
#
# Usage:
# expand_grid([0, 1], [2,3,4])
#
# Output:
# array([[0, 2],
# [1, 2],
# [0, 3],
# [1, 3],
# [0, 4],
# [1, 4]])
import numpy as np
from functools import reduce
def expand_grid(*arrs):
ncols = len(arrs)
nrows = reduce(lambda x, y: x * y, map(len, arrs), 1)
return np.array(np.meshgrid(*arrs)).reshape(ncols, nrows).T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment