Categories
dataframe pandas python

Unnest (explode) a Pandas Series

I have:

df = pd.DataFrame({'col1': ['asdf', 'xy', 'q'], 'col2': [1, 2, 3]})
col1 col2
0 asdf 1
1 xy 2
2 q 3

I’d like to take the “combinatoric product” of each letter from the strings in col1, with each elementwise int in col2. I.e.:

  col1  col2
0 a 1
1 s 1
2 d 1
3 f 1
4 x 2
5 y 2
6 q 3

Current method:

from itertools import product
pieces = []
for _, s in df.iterrows():
letters = list(s.col1)
prods = list(product(letters, [s.col2]))
pieces.append(pd.DataFrame(prods))
pd.concat(pieces)

Any more efficient workarounds?