s_khan92
s_khan92

Reputation: 979

How to make combination based on other column in Panda dataframe

I have a dataframe with keywords column. Keywords column has also 2-7 keywords which are separated by comma. For example:

URL                                    Keywords
www.example.com                   "Keyword 1 , Keyword 2 , Keyword 3"
www.example2.com                  "Keyword 2, Keyword 4, Keyword 5"
.
.
.

i want the output which generate combinations but only two. I need actually values for "TO" and "FROM" for visualization. I expect the output in this way

URL                      Keyword Combination
www.example.com          Keyword 1, Keyword 2
www.example.com          Keyword 1, Keyword 3
www.example.com          Keyword 2, Keyword 1
www.example.com          Keyword 2, Keyword 3
.
.
.
.

I think it will be possible with ITERTOOLS but i am not sure how i can implement on this.

Upvotes: 1

Views: 56

Answers (1)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Try itertools.permutation, itertools.chain, and df.explode (for pandas >= 0.25.0):

>>> lst = [[','.join(p) for p in permutations(val.split(','),2)] for val in df['Keywords']]
>>> df['Keywords'] = lst
>>> df.explode('Keywords')

  URL                                                    Keywords
0      www.example.com                     Keyword 1 , Keyword 2 
0      www.example.com                      Keyword 1 , Keyword 3
0      www.example.com                      Keyword 2 ,Keyword 1 
0      www.example.com                      Keyword 2 , Keyword 3
0      www.example.com                       Keyword 3,Keyword 1 
0      www.example.com                      Keyword 3, Keyword 2 
1      www.example2.com                      Keyword 2, Keyword 4
1      www.example2.com                      Keyword 2, Keyword 5
1      www.example2.com                       Keyword 4,Keyword 2
1      www.example2.com                      Keyword 4, Keyword 5
1      www.example2.com                       Keyword 5,Keyword 2
1      www.example2.com                      Keyword 5, Keyword 4

Upvotes: 1

Related Questions