Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix Multiplication of a Pandas DataFrame and Series

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?

like image 577
nitin Avatar asked Mar 15 '13 17:03

nitin


People also ask

How do you do matrix DataFrame multiplication?

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.

How do pandas multiply to Series?

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.

How do pandas multiply data frames?

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.

How do you convert a DataFrame to a matrix in Python?

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.


1 Answers

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
like image 183
Jeff Avatar answered Oct 13 '22 23:10

Jeff