I want to do a matrix multiplcation of a pandas dataframe and a series
df = pandas.DataFrame({'a':[4,1,3], 'b':[5,2,4]},index=[1,2,3])
ser = pandas.Series([0.6,0.4])
df is,
a b
1 4 5
2 1 2
3 3 4
ser is,
0 0.6
1 0.4
My desired result is a matrix product, like so
ans is,
I can do this by using numpy dot operator and rebuilding my dataFrame
c = a.values.dot(b.transpose())
c = pandas.DataFrame(c, index = a.index, columns = ['ans'])
print c
ans
1 4.4
2 1.4
3 3.4
Is there a native method in pandas to do this?
The dot() method of pandas DataFrame class does a matrix multiplication between a DataFrame and another DataFrame, a pandas Series or a Python sequence and returns the resultant matrix.
The mul() method of the pandas Series multiplies the elements of one pandas Series with another pandas Series returning a new Series. Multiplying of two pandas. Series objects can be done through applying the multiplication operator “*” as well.
The mul() method of DataFrame object multiplies the elements of a DataFrame object with another DataFrame object, series or any other Python sequence. mul() does an elementwise multiplication of a DataFrame with another DataFrame, a pandas Series or a Python Sequence.
A two-dimensional rectangular array to store data in rows and columns is called python matrix. Matrix is a Numpy array to store data in rows and columns. Using dataframe. to_numpy() method we can convert dataframe to Numpy Matrix.
pandas implicity aligns on the index of a series, use the dot function
In [3]: df = pd.DataFrame({'a' : [4,1,3], 'b' : [5,2,4]},index=[1,2,3])
In [4]: s = pd.Series([0.6,0.4],index=['a','b'])
In [5]: df.dot(s)
Out[5]:
1 4.4
2 1.4
3 3.4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With