2.13 Creating Example Data

To create a dataframe from every combination of some given values, like R’s expand.grid() function, we can create a dict where the keys are column names and the values are lists of the data values:

In [1]: def expand_grid(data_dict):
   ...:    rows = itertools.product(*data_dict.values())
   ...:    return pd.DataFrame.from_records(rows, columns=data_dict.keys())
   ...: 

In [2]: df = expand_grid(
   ...:    {'height': [60, 70],
   ...:     'weight': [100, 140, 180],
   ...:     'sex': ['Male', 'Female']})
   ...: 

In [3]: df
Out[3]: 
       sex  weight  height
0     Male     100      60
1     Male     100      70
2     Male     140      60
3     Male     140      70
..     ...     ...     ...
8   Female     140      60
9   Female     140      70
10  Female     180      60
11  Female     180      70

[12 rows x 3 columns]