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

Looping through pairwise combinations of columns

Here is an example dataframe:

d = {'Gender': [1,1,0,1,0], 'Employed': [1,0,0,1,1], 'Name':['Alan', 'Joe', 'Sam', 'Amy', 
'Chloe']}
d=pd.DataFrame(d)

I wanted to get all pairwise combinations of the columns so I could pass them into a fisher’s exact test:

from itertools import combinations
pairwise_combinations=list(combination(d.columns, 2))
pairwise_combinations=[', '.join(map(str, x)) for x in pairwise_combinations]

This gives me the pairs in the form:

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

Gender, Employed

I want to be able to say

for i in pairwise_combinations:
    data=d[[i]]

At the moment this gives an error because it is still in the wrong form. I need quotes around the column names. How can I do this?

>Solution :

If I understand well what you want is this :

from itertools import combinations
pairwise_combinations = list(combinations(d.columns, 2))

for i in pairwise_combinations:
    data = d.loc[:, i]
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