Skip to content

Commit 69bb0e8

Browse files
Merge pull request #7556 from onesandzeroes/expand-grid
DOC: Cookbook recipe for emulating R's expand.grid() (#7426)
2 parents c079290 + b642ee7 commit 69bb0e8

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

doc/source/cookbook.rst

+22
Original file line numberDiff line numberDiff line change
@@ -663,3 +663,25 @@ To globally provide aliases for axis names, one can define these 2 functions:
663663
df2 = DataFrame(randn(3,2),columns=['c1','c2'],index=['i1','i2','i3'])
664664
df2.sum(axis='myaxis2')
665665
clear_axis_alias(DataFrame,'columns', 'myaxis2')
666+
667+
Creating Example Data
668+
---------------------
669+
670+
To create a dataframe from every combination of some given values, like R's ``expand.grid()``
671+
function, we can create a dict where the keys are column names and the values are lists
672+
of the data values:
673+
674+
.. ipython:: python
675+
676+
import itertools
677+
678+
def expand_grid(data_dict):
679+
rows = itertools.product(*data_dict.values())
680+
return pd.DataFrame.from_records(rows, columns=data_dict.keys())
681+
682+
df = expand_grid(
683+
{'height': [60, 70],
684+
'weight': [100, 140, 180],
685+
'sex': ['Male', 'Female']}
686+
)
687+
df

0 commit comments

Comments
 (0)