How to convert the dataframe to a desired format?

Viewed 57

I'm looking to convert the dataframe to particular format.

The example dataframe is as follows:

Col1
a
b
c

I want to convert the above dataframe to following format by splitting into two columns:

Col1  Col2
a      a
a      b
a      c
b      b
b      c
c      c

I am trying to get all the combinations of the Col1 column.

2 Answers

You could try itertools.combinations_with_replacement:

from itertools import combinations_with_replacement as comb
df = pd.DataFrame(list(comb(df['Col1'], 2)), columns=['Col1', 'Col2'])
print(df)

Output:

  Col1 Col2
0    a    a
1    a    b
2    a    c
3    b    b
4    b    c
5    c    c
>>> 

Edit:

Thanks to @QuangHoang's comment, he mentioned that for higher versions (Quang Hoang has 1.1.4), you can do:

df = pd.DataFrame(comb(df['Col1'], 2), columns=['Col1', 'Col2'])

Without the list(...). Whereas for lower versions you get:

TypeError: data argument can't be an iterator

Looks like a cross merge:

df['key'] = 1

df.merge(df,on='key').query('Col1_x<=Col1_y').drop(['key'],axis=1)

Output:

  Col1_x Col1_y
0      a      a
1      a      b
2      a      c
4      b      b
5      b      c
8      c      c
Related