-1

I have two lists

list1=['a','b','c']

list2=[1,2]

I want my dataframe output to look like:

col1     col2
a        1
a        2
b        1
b        2
c        1
c        2

How can this be done?

martineau
  • 119,623
  • 25
  • 170
  • 301
dcrowley01
  • 141
  • 2
  • 12
  • Does this answer your question? [cartesian product in pandas](https://stackoverflow.com/questions/13269890/cartesian-product-in-pandas) – Mateen Ulhaq Jun 02 '20 at 17:59
  • 1
    See second answer: https://stackoverflow.com/a/46744050/365102... hmmm I guess it's not really an *exact* duplicate. – Mateen Ulhaq Jun 02 '20 at 17:59

2 Answers2

3

Use itertools.product:

import itertools

list1 = ['a','b','c']
list2 = [1,2]
df = pd.DataFrame(itertools.product(list1, list2), columns=['col1', 'col2'])
print(df)

Output:

  col1  col2
0    a     1
1    a     2
2    b     1
3    b     2
4    c     1
5    c     2
jfaccioni
  • 7,099
  • 1
  • 9
  • 25
0

If you don't want to explicitly import itertools, pd.MultiIndex has a from_product method that you might piggyback on:

list1 = ['a','b','c']
list2 = [1, 2]
pd.DataFrame(pd.MultiIndex.from_product((list1, list2)).to_list(), columns=['col1', 'col2'])
  col1  col2
0    a     1
1    a     2
2    b     1
3    b     2
4    c     1
5    c     2
r.ook
  • 13,466
  • 2
  • 22
  • 39