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.
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With