marupav marupav -4 years ago 48
Python Question

How to get required combinations from different rows of column in python

I am trying to get the different required combinations out from dataframe column with few rows.It is something like below:
I have following values in one of the columns of my df

Oy
On
G1
G2
A1
A2
A3
A4
R1
R2
R3
L1
L2
A5
A6


Here oy,on belong to group 1,

G1,g2 - group 2,
A1 to a4 - group 3,
R1 to r3 - group 4,
L1,l2 - group 5,
A5,a6 - group 6


Now I am trying all the combinations from each value of the each group ranging from 1 value to all like below:

Oy
Oy g1
Oy g1 a1
Oy g1 a1 r1
Oy g1 a1 r1 l1
Oy g1 a1 r1 l1 a5


This will be for all possible combinations.note that within group combination is not desirable like g1 and g2 cannot come in same combination.

I know that this is possible with for loops with some if conditions.But looking for more efficient and elegant solution.

Answer Source

I think you may want to itertools.product on the various groupings. To get the groups you could do

first_letter = df[col].str[0].str.lower()
groups = df[col].groupby(first_letter).unique()

(col here is the name of the column describe above).

This gives a mapping from the first letter (lowercase) to an array of the unique values starting with that letter (lower or upper case). Then you can do itertools.product(*groups) to get all six-tuples containing one member from each group. To get all combinations of, say, the g and o groups, you can do itertools.product(*groups[['g', 'o']])

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download