Dan Grossnickle
Dan Grossnickle

Reputation: 45

python pandas crosstab sumproduct square matrix

i'm looking for help creating a sub-dataframe from an existing dataframe using a sumproduct-like function. I want to convert this table, into a small sum product using the column headings:

    dan ste bob
t1  0   2   0
t2  2   0   1
t3  2   1   0
t4  1   0   2
t5  0   1   2

Column heading become index and sum product is the value:

    dan ste bob
dan 9   2   4
ste 2   6   2
bob 4   2   9

dan x dan = 9 (0*0)+(2*2)+(2*2)+(1*1)+(0*0)

Thanks in advance!

Upvotes: 1

Views: 510

Answers (2)

BENY
BENY

Reputation: 323276

You should using .dot this is just for fun

df1=pd.DataFrame(index=df.columns,columns=df.columns)
df1.apply(lambda x : [sum(df[x.name]*df[y]) for y in x.index])
Out[65]: 
     dan  ste  bob
dan    9    2    4
ste    2    6    2
bob    4    2    9

Upvotes: 0

Andy Hayden
Andy Hayden

Reputation: 375535

You can use the dot with its transpose:

In [11]: df.T.dot(df)
Out[11]:
     dan  ste  bob
dan    9    2    4
ste    2    6    2
bob    4    2    9

Upvotes: 2

Related Questions