Home > OS >  expand.grid equivalent to get pandas data frame for prediction in Python
expand.grid equivalent to get pandas data frame for prediction in Python

Time:02-15

In R can quite easily do:

expand.grid(a = c(1,2,3), b = c(4,5))

to get a data frame:

enter image description here

I think something like this may work in Python:

from sklearn.model_selection import ParameterGrid

param_grid = {'a': [1,2,3], 'b': [4,5]}
expanded_grid = ParameterGrid(param_grid)

but being a converter from R to Python I would not know if this the best way and how to get a pandas data frame, ultimately to be used for predictions. Thanks!

CodePudding user response:

In pandas we have MultiIndex

d =  {'a': [1, 2, 3], 'b': [4, 5]}
out = pd.MultiIndex.from_product(d.values(),names=d.keys()).to_frame().reset_index(drop=True)
Out[58]: 
   a  b
0  1  4
1  1  5
2  2  4
3  2  5
4  3  4
5  3  5

or simple with itertools

import itertools
out = pd.DataFrame(itertools.product(*d.values()),columns=d.keys())
Out[62]: 
   a  b
0  1  4
1  1  5
2  2  4
3  2  5
4  3  4
5  3  5
  • Related