Matrix Multiplication of a Pandas DataFrame and Series

nitin picture nitin · Mar 15, 2013 · Viewed 12.2k times · Source

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?

Answer

Jeff picture Jeff · Mar 15, 2013

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