Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all combinations of elements from two lists?

Tags:

python

pandas

If I have two lists

l1 = [ 'A', 'B' ]  l2 = [ 1, 2 ] 

what is the most elegant way to get a pandas data frame which looks like:

+-----+-----+-----+ |     | l1  | l2  | +-----+-----+-----+ |  0  | A   | 1   | +-----+-----+-----+ |  1  | A   | 2   | +-----+-----+-----+ |  2  | B   | 1   | +-----+-----+-----+ |  3  | B   | 2   | +-----+-----+-----+ 

Note, the first column is the index.

like image 662
K.Chen Avatar asked Sep 03 '14 00:09

K.Chen


People also ask

How do you generate all possible combinations of two lists?

Add a Custom Column to and name it List1. Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.


1 Answers

use product from itertools:

>>> from itertools import product >>> pd.DataFrame(list(product(l1, l2)), columns=['l1', 'l2'])   l1  l2 0  A   1 1  A   2 2  B   1 3  B   2 
like image 96
behzad.nouri Avatar answered Oct 07 '22 19:10

behzad.nouri