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.
>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