Pandas 数据帧和系列的矩阵乘法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15438952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:42:39  来源:igfitidea点击:

Matrix Multiplication of a Pandas DataFrame and Series

pythonpandasmatrixmatrix-multiplicationdot-product

提问by nitin

I want to do a matrix multiplcation of a pandas dataframe and a series

我想做一个Pandas数据框和一个系列的矩阵乘法

df = pandas.DataFrame({'a':[4,1,3], 'b':[5,2,4]},index=[1,2,3])
ser = pandas.Series([0.6,0.4])

df is,

df 是,

 a  b
1  4  5
2  1  2
3  3  4

ser is,

ser是,

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

我可以通过使用 numpy 点运算符并重建我的数据帧来做到这一点

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?

大Pandas是否有本地方法来做到这一点?

回答by Jeff

pandas implicity aligns on the index of a series, use the dot function

pandas 隐式对齐在一个系列的索引上,使用 dot 函数

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