Missm
Missm

Reputation: 39

How do I iterate through a data frame to print all possible combinations of two list columns?

Lets say I have a datavframe:

Column1 Column2
1 A
2 A, B
3 A, B, C

I want to print every possible combination from the two lists on a new row. The output should look something like:

1A
2A 
2B
3A 
3B 
3C

Upvotes: 0

Views: 319

Answers (4)

SomeDude
SomeDude

Reputation: 14238

Another way to use itertools.product:

from itertools import product
import re
out = df.apply(lambda x: list(
                product([str(x['Column1'])], list(re.sub('\s*,\s*', '', x['Column2'])))),
               axis=1)
out = [''.join(b) for a in out for b in a]

print(out):

['1A', '2A', '2B', '3A', '3B', '3C']

Upvotes: 1

Nuri Taş
Nuri Taş

Reputation: 3845

Another possible solution:

df.apply(lambda x: [str(x.Column1) + item for item in x.Column2.split(', ')], axis=1).explode()

Upvotes: 1

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

Let's try split Column2 into list then explode Column2. At last join two columns and convert to list.

out = (df.assign(Column2=df['Column2'].str.split(', '))
       .explode('Column2')
       # [['Column1', 'Column2']] # uncomment this line if there are more than two target columns
       .astype(str)
       .agg(''.join, axis=1)
       .tolist())
print(out)

['1A', '2A', '2B', '3A', '3B', '3C']

Upvotes: 1

mozway
mozway

Reputation: 262079

Better use pure python here:

from itertools import product
out = [''.join(x) for a,b in zip(df['Column1'], df['Column2'])
       for x in product([str(a)], b.split(', '))]

output: ['1A', '2A', '2B', '3A', '3B', '3C']

Classical loop:

for a,b in zip(df['Column1'], df['Column2']):
    for x in product([str(a)], b.split(', ')):
        print(''.join(x))

output:

1A
2A
2B
3A
3B
3C

Upvotes: 1

Related Questions