Created
June 4, 2022 16:03
-
-
Save fauxneticien/2ff31c5ec32e2545e9bf749fc9b15d08 to your computer and use it in GitHub Desktop.
Python equivalent for R's expand grid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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