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

Support Matrix for Boolean DataFrame

So I have a one-hot encoding called datBaskets. Rows are transactions, and columns are store departments. The ijth entry is true if the ith basket contains an item from the jth department and false otherwise. It looks something like this…

Cleaning Supplies Batteries Food
0 True True False
1 False True True
2 False False False
3 True False False
4 True False True
5 False True False

What I seek is a matrix with departments as both rows and columns that tells me the proportion of all transactions that contain that combination of departments. So the Batteries-Food entry would be 0.167 in this case.

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

>Solution :

from io import StringIO

import numpy as np
import pandas as pd

s = """
Cleaning Supplies,Batteries,Food
True,True,False
False,True,True
False,False,False
True,False,False
True,False,True
False,True,False
"""

# read in your data
df = pd.read_csv(StringIO(s))

ncols = len(df.columns)
matrix = np.zeros((ncols, ncols))  # initialize empty array

# go through each point in matrix and assign value (this will take the % of True, True combinations)
for i, col1 in enumerate(df.columns):
    for j, col2 in enumerate(df.columns):
        matrix[i, j] = (df[col1] * df[col2]).mean()

df_matrix = pd.DataFrame(matrix, columns=df.columns, index=df.columns)  # create a data frame that labels indices and columns

Then df_matrix will look like this:

                    Cleaning Supplies   Batteries   Food
Cleaning Supplies   0.500000            0.166667    0.166667
Batteries           0.166667            0.500000    0.166667
Food                0.166667            0.166667    0.333333
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