Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a matrix from a column and a row

Tags:

python

pandas

What is the most elegant way to multiply a column and a row together to make a matrix.

I want to take two series and make a dataframe from them with the length of one series and the width of another. In this case I want to multiply the two.

sr1 = 
0     2
1     3     
2     4

sr2 = 
0         0
1        10
2        100
3        50

Desired result: a dataframe where sr1 = y axis, sr2 = x axis

0   20   200   100
0   30   300   150
0   40   400   200

Is there a simple function in pandas or something similar that does this without first repeating a series as columns in a df and then multiplying?

like image 221
Ginger Slice Avatar asked Jan 24 '23 20:01

Ginger Slice


1 Answers

Check numpy.multiply.outer

import numpy as np 

df=pd.DataFrame(np.multiply.outer(sr1.values,sr2.values))
Out[11]: 
   0   1    2    3
0  0  20  200  100
1  0  30  300  150
2  0  40  400  200
like image 90
BENY Avatar answered Jan 27 '23 10:01

BENY