2

id and st

id = [243,2352,474, 84,443]
st = [1,3,5,9,2,6,7]

I wish to create a pandas dataframe df using them so that each value of the list id have all values from st list.

My expected output is like:

id    st
243   1
243   3
243   5
243   9
243   2
243   6
243   7
2352  1
2352  3
2352  5
2352  9
2352  2
2352  6
2352  7

and so on...

How can I create the same pandas dataframe ?

Archit
  • 542
  • 1
  • 4
  • 15
  • Does this answer your question? [Get all combinations of elements from two lists?](https://stackoverflow.com/questions/25634489/get-all-combinations-of-elements-from-two-lists) – Georgy May 29 '20 at 12:13

3 Answers3

1

Use itertools.product with DataFrame constructor:

from  itertools import product
#pandas 0.24+
df = pd.DataFrame(product(id, st), columns = ['id','st'])
#pandas below
#df = pd.DataFrame(list(product(id, st)), columns = ['id','st'])

print (df)
      id  st
0    243   1
1    243   3
2    243   5
3    243   9
4    243   2
5    243   6
6    243   7
7   2352   1
8   2352   3
9   2352   5
10  2352   9
11  2352   2
12  2352   6
13  2352   7
14   474   1
15   474   3
16   474   5
17   474   9
18   474   2
19   474   6
20   474   7
21    84   1
22    84   3
23    84   5
24    84   9
25    84   2
26    84   6
27    84   7
28   443   1
29   443   3
30   443   5
31   443   9
32   443   2
33   443   6
34   443   7
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

Use list comprehension with the pandas.DataFrame constructor:

df = pd.DataFrame([(i, s) for i in id for s in st], columns=['id', 'st'])

[out]

     id  st
0   243   1
1   243   3
2   243   5
3   243   9
4   243   2
5   243   6
6   243   7
7  2352   1
8  2352   3
9  2352   5
...
25   84   2
26   84   6
27   84   7
28  443   1
29  443   3
30  443   5
31  443   9
32  443   2
33  443   6
34  443   7
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
0

Try below code, if it helps:

pd.DataFrame({'id': sorted(id * len(st)), 'st': st * len(id)})

hacker315
  • 1,996
  • 2
  • 13
  • 23