Reputation: 59
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?
Upvotes: 4
Views: 87
Reputation: 25239
Use broadcasting
pd.DataFrame(s2.values * s1.values[:,None])
Out[585]:
0 1 2 3
0 0 20 200 100
1 0 30 300 150
2 0 40 400 200
Upvotes: 3
Reputation: 323226
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
Upvotes: 5