Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Interleave a list and distribute to two columns of a dataframe by pandas?

I have a list and I want to interleave the elements in all combinations then distribute them to two columns of a dataframe by pandas, like:

df = pd.DataFrame(columns = ["pair1","pair2"])

mylist = ["a", "b", "c"]

for i in mylist:

    for j in mylist:

        df.loc[df.shape[0]] = [i, j]

to output

    pair1   pair2
0   a   a
1   a   b
2   a   c
3   b   a
4   b   b
5   b   c
6   c   a
7   c   b
8   c   c

However, such an assignment is slow.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Do we have a faster method?

>Solution :

For a pandas solution, you could use pd.MultiIndex:

df[['pair1','pair2']] = pd.MultiIndex.from_product([mylist]*2).tolist()

or you could also cross-merge (if you have pandas>=1.2.0):

df = pd.merge(pd.Series(mylist, name='pair1'), pd.Series(mylist, name='pair2'), how='cross')

Output:

  pair1 pair2
0     a     a
1     a     b
2     a     c
3     b     a
4     b     b
5     b     c
6     c     a
7     c     b
8     c     c
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading