user10784511
user10784511

Reputation:

How to get the combinations of a group from a column in pandas

I have a df with the column keyword:

Keyword   
A          
A          
A         
B
B
B
C
C
D
D

i am dividing into groups using the following code

df_unique = df.groupby('Keyword').nunique()

But i want the combinations of the unique groups from the column.

o/p:

AB
AC
AD
BC
BD
CD

Upvotes: 1

Views: 29

Answers (1)

jezrael
jezrael

Reputation: 862511

Use combinations with list comprehension and f-strings for join tuples:

from  itertools import combinations
L = [f'{a}{b}' for a, b in combinations(df['Keyword'].unique(), 2)]
print (L)
['AB', 'AC', 'AD', 'BC', 'BD', 'CD']

df1 = pd.DataFrame({'comb':L})
print (df1)
  comb
0   AB
1   AC
2   AD
3   BC
4   BD
5   CD

For 2 columns:

from  itertools import combinations
L1 = list(combinations(df['Keyword'].unique(), 2))
print (L1)
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

df1 = pd.DataFrame(L1, columns=['comb1','comb2'])
print (df1)
  comb1 comb2
0     A     B
1     A     C
2     A     D
3     B     C
4     B     D
5     C     D

Upvotes: 1

Related Questions